并行计算基础 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;
}
相关推荐
小龙报2 分钟前
《算法每日一题(1)--- 连续因子》
c语言·开发语言·c++·windows·git·算法·visual studio
祁同伟.8 分钟前
【C++】异常
开发语言·c++
yuuki2332338 分钟前
【C语言】程序的编译和链接(基础向)
c语言·后端
第七序章24 分钟前
【C + +】红黑树:全面剖析与深度学习
c语言·开发语言·数据结构·c++·人工智能
夜晚中的人海28 分钟前
【C++】滑动窗口算法习题
开发语言·c++·算法
AA陈超1 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-09 玩家等级与战斗接口
c++·游戏·ue5·游戏引擎·虚幻
violet-lz1 小时前
数据结构四大简单排序算法详解:直接插入排序、选择排序、基数排序和冒泡排序
数据结构·算法·排序算法
·白小白1 小时前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
tongsound1 小时前
libmodbus 使用示例
linux·c++
sulikey2 小时前
C++的STL:深入理解 C++ 的 std::initializer_list
开发语言·c++·stl·list·initializerlist·c++标准库