1. 程式人生 > >c++ 多執行緒 鎖(互斥鎖)

c++ 多執行緒 鎖(互斥鎖)

多執行緒程式,如果涉及到對共享資源的併發讀寫,就會產生資源爭用(Data Race)。解決資源爭用,最直接的想法是引入鎖,對併發讀寫的資料進行保護(更高階的則包括無鎖程式設計—— Lock Free Programming)。但是,鎖又有很多種類,例如:自旋鎖(Spinlock)、互斥鎖(Mutex)、讀寫鎖(Read-Write-Lock)等等。

1.多執行緒使用互斥鎖

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h> 
using namespace std;
#define NUM_THREADS    10

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int count =0; 
struct thread_data{
   int  thread_id;
   char *message;
};
 
void *PrintHello(void *threadarg)
{
int k=10000;
   struct thread_data *my_data;
 
   my_data = (struct thread_data *) threadarg;
 
   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;
        while(k--){
pthread_mutex_lock(&mut);
        count++;
pthread_mutex_unlock(&mut);
        }
 
   pthread_exit(NULL);
}
int main ()
{
   pthread_t threads[NUM_THREADS];
   struct thread_data td[NUM_THREADS];
   int rc;
   int i;
 
   for( i=0; i < NUM_THREADS; i++ ){
      cout <<"main() : creating thread, " << i << endl;
      td[i].thread_id = i;
      td[i].message = (char*)"This is message";
      rc = pthread_create(&threads[i], NULL,
                          PrintHello, (void *)&td[i]);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
        for(int k=0;k<NUM_THREADS;k++){
                pthread_join(threads[k],NULL);
        }
        cout<<"count----------:"<<count<<endl;
        pthread_mutex_destroy(&mut);
   pthread_exit(NULL);
}