pthread并行计算互斥锁的使用

2015-01-27 14:03:04 · 作者: · 浏览: 14

由于pthread实现并行计算的方式是基于共享内存的,因此在多线程中共享变量的使用存在诸多同步性问题。在多个线程中对同一个变量进行读的时候可能没问题,但是在修改的时候,就有可能造成变量内容的不一致。为了解决这个问题,就需要对共享变量进行互斥的访问。

为了实现这一功能,在pthread中提供了线程锁,通过加锁和解锁就可以轻松避免上述问题,具体实例如下:

#include
  
   
#include
   
     #include
    
      #include
     
       using namespace std; vector
      
        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;
  for(int i=0;i
   
    ::iterator it; for(it=vec.begin();it!=vec.end();it++) //print the result cout<<*it<
    
     
在上述代码中实现了使用多线程向vector添加元素,并在主线程中打印出来。需要说明的是,如果在hello中如果不使用互斥锁,程序运行将出现错误。可能是pthread内部对多线程进行了限制,以避免出现类似错误。