pthread并行计算互斥锁的使用

来源:互联网 发布:js json操作 编辑:程序博客网 时间:2024/06/08 02:56

     由于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);}

在上述代码中实现了使用多线程向vector添加元素,并在主线程中打印出来。需要说明的是,如果在hello中如果不使用互斥锁,程序运行将出现错误。可能是pthread内部对多线程进行了限制,以避免出现类似错误。

0 0