并行计算基础 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;
}
相关推荐
HalvmånEver3 小时前
在 C++ :x86(32 位)和 x64(64 位)的不同
开发语言·c++·学习
legendary_bruce6 小时前
【22-决策树】
算法·决策树·机器学习
浪成电火花6 小时前
(deepseek!)deepspeed中C++关联部分
开发语言·c++
max5006007 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
谱写秋天8 小时前
FreeRTOS中断服务程序(ISR)详细讲解
c语言·freertos·isr
愿天堂没有C++8 小时前
剑指offer第2版——面试题4:二维数组中的查找
c++·面试
快去睡觉~9 小时前
力扣400:第N位数字
数据结构·算法·leetcode
徐归阳9 小时前
第二十四天:虚函数与纯虚函数
c++
青草地溪水旁10 小时前
UML函数原型中constraint的含义,有啥用?
c++·uml
qqxhb10 小时前
零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
算法·搜索引擎·tf-idf·倒排索引·pagerank·算法库