并行计算基础 c cpp不同格式,不同套路。

cpp 复制代码
#include <stdio.h>
#include <pthread.h>
void* func(void* args) {
  printf("hello world from tid = %ld\n", pthread_self());
  return NULL;
}
int main() {
  pthread_t threads[4];
  for(int i = 0; i < 4; i++) {
    pthread_create(&threads[i], NULL, func, NULL);
  }
  for(int i = 0; i < 4; i++) {
    pthread_join(threads[i], NULL);
  }
  return 0;
}
cpp 复制代码
#include <stdio.h>
#include <pthread.h>
void* func(void* args) {
  printf("hello world from tid = %ld\n", pthread_self());
  return NULL;
}
int main() {
  pthread_t threads[4];
  for(int i = 0; i < 4; i++) {
    pthread_create(&threads[i], NULL, func, NULL);
  }
  for(int i = 0; i < 4; i++) {
    pthread_join(threads[i], NULL);
  }
  return 0;
}
cpp 复制代码
#include <stdio.h>
#include <omp.h>
int main() {
  // #pragma 表示这是编译指导语句 表示编译器需要对下面的并行域进行特殊处理
  // omp parallel 表示下面的代码区域 {} 是一个并行域 
  //num_threads(4) 表示一共有 4 个线程执行 {} 内的代码 
  //因此实现的效果和上面的效果是一致的
  #pragma omp parallel num_threads(4)
  {
    printf("hello world from tid = %d\n", omp_get_thread_num()); // omp_get_thread_num 表示得到线程的线程 id
  }
  return 0;
}
//gcc openMP.c -o mainopenMP.exe -fopenmp
cpp 复制代码
//y=x*x 在0到10区间的积分

#include <stdio.h>
#include <omp.h>
#include <math.h>
/// @brief 计算 x^2 一部分的面积
/// @param start 线程开始计算的位置
/// @param end   线程结束计算的位置
/// @param delta 长方形的边长
/// @return 计算出来的面积
double x_square_partial_integral(double start, double end, double delta) {
  double s = 0;
  for(double i = start; i < end; i += delta) {
    s += pow(i, 2) * delta;
  }
  return s;
}
int main() {
  int s = 0;
  int e = 10;
  double sum = 0;
  #pragma omp parallel num_threads(32) reduction(+:sum)
  {
    // 根据线程号进行计算区间的分配
    // omp_get_thread_num() 返回的线程 id 从 0 开始计数 :0, 1, 2, 3, 4, ..., 31
    double start = (double)(e - s) / 32 * omp_get_thread_num();
    double end   = (double)(e - s) / 32 * (omp_get_thread_num() + 1);
    sum = x_square_partial_integral(start, end, 0.0000001);
  }
  printf("sum = %lf\n", sum);
  return 0;
}
相关推荐
FirstFrost --sy1 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森1 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼1145141 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)2 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle2 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
无聊的小坏坏3 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   3 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
山河木马3 小时前
前端学习C++之:.h(.hpp)与.cpp文件
前端·javascript·c++
2401_891957313 小时前
list的一些特性(C++)
开发语言·c++
秋说3 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法