并行计算基础 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;
}
相关推荐
G.E.N.2 分钟前
开源!RAG竞技场(2):标准RAG算法
大数据·人工智能·深度学习·神经网络·算法·llm·rag
写个博客6 分钟前
暑假算法日记第三天
算法
✿ ༺ ོIT技术༻32 分钟前
剑指offer第2版:动态规划+记忆化搜索
算法·动态规划·记忆化搜索
算法练习生1 小时前
Qt核心类QWidget及其派生类详解
开发语言·c++·qt
oioihoii1 小时前
C++11标准库算法:深入理解std::none_of
java·c++·算法
阿捏利1 小时前
【加解密与C】非对称加解密(二)ELGamel
c语言·加解密·elgamel
1024小神1 小时前
tauri项目在windows上的c盘没有权限写入文件
c语言·开发语言·windows
karmueo463 小时前
视频序列和射频信号多模态融合算法Fusion-Vital解读
算法·音视频·多模态
小汉堡编程4 小时前
数据结构——vector数组c++(超详细)
数据结构·c++
写代码的小球6 小时前
求模运算符c
算法