pthread并行计算入门

这篇博客介绍了pthread库作为并行计算的一种实现方式,重点在于其共享内存的特性,允许CPU访问相同内存区域,但同时也可能导致临界区问题。文中通过示例代码展示了如何创建线程、传递参数和获取返回值。
摘要由CSDN通过智能技术生成

     实现并行的库有很多,比如mpi库,openmp等,同样pthread也是实现并行的一个库。pthread实现并行的是共享内存的方式,即如何CPU都可以访问相同的内存区域。这种实现方式实现起来比较简单,但是会存在临界区等问题。

以下是最简单的一段并行的代码,其实现了创建多个线程,为多线程函数传递参数,从多线程函数获取返回值等操作,

#include<iostream>
#include<pthread.h>
#include<stdlib.h>

using namespace std;

int thread_count;
void *hello(void* a)
{
  int aa = (int)a;    //convert a to int
  //cout << "I am aa :" << aa << endl;
  return (void *)(aa+1);
}
int main()
{
  pthread_t threads[4];  
  int thread_count = 4;

  for(int thread = 0;thread<thread_count;thread++)
  {
    pthread_create(&threads[thread],NULL,hello,(void*)thread);//hello is the function that the new thread will execute,and the thread is the parameters
  }
  
  cout << "I am main." << endl;

  void **getReturn;            //recieve the return from the threads
  for(i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值