并行计算基础 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;
}
相关推荐
Swift社区3 分钟前
LeetCode 462 - 最小操作次数使数组元素相等 II
算法·leetcode·职场和发展
nike0good13 分钟前
Goodbye 2025 题解
开发语言·c++·算法
Sheep Shaun14 分钟前
STL中的unordered_map和unordered_set:哈希表的快速通道
开发语言·数据结构·c++·散列表
崇山峻岭之间15 分钟前
Matlab学习记录19
学习·算法·matlab
jllllyuz18 分钟前
基于帧差法与ViBe算法的MATLAB前景提取
开发语言·算法·matlab
wen__xvn37 分钟前
代码随想录算法训练营DAY1第一章 数组part01
数据结构·算法·leetcode
樊梓慕41 分钟前
【嵌入式】buildroot构建ros2环境
c++·机器人
爱编码的傅同学42 分钟前
【程序地址空间】页表的映射方式
c语言·数据结构·c++·算法
序属秋秋秋42 分钟前
《Linux系统编程之进程控制》【进程替换】
linux·c语言·c++·操作系统·进程·系统编程·进程替换
hslinux1 小时前
NDK 通过configure 编译C++源码通用脚本
android·c++·ndk·configure