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

猜你喜欢

转载自blog.csdn.net/weixin_42627035/article/details/85702565