由于pthread实现并行计算的方式是基于共享内存的,因此在多线程中共享变量的使用存在诸多同步性问题。在多个线程中对同一个变量进行读的时候可能没问题,但是在修改的时候,就有可能造成变量内容的不一致。为了解决这个问题,就需要对共享变量进行互斥的访问。
为了实现这一功能,在pthread中提供了线程锁,通过加锁和解锁就可以轻松避免上述问题,具体实例如下:
#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<vector>
using namespace std;
vector<int> vec;
pthread_mutex_t mutex;
int thread_count;
void *hello(void* a)
{ int aa = (int)a;
pthread_mutex_lock(&mutex); //加锁
vec.push_back(aa);
pthread_mutex_unlock(&mutex); //解锁
}
int main()
{
pthread_t threads[4];
thread_count = 4;
pthread_mutex_init(&mutex,NULL);
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;
cin >> thread_count;
for(int i=0;i<thread_count;i++)
{
pthread_join(threads[i],NULL); //stop all the threads
}
vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++) //print the result
cout<<*it<<endl;
//free(threads);
}
原文地址:http://blog.csdn.net/gaoxiang__/article/details/40592255