实现并行的库有很多,比如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