在两个线程中安全地修改变量

Safely modifying variable in two threads

考虑以下人为的例子-

假设我有一个修改全局变量的线程:

void thread_1(void* param) {
    for (int i=0; i<10; i++) {
        x += i; // x is global.
    }
}

假设我有另一个修改同一个全局变量的线程:

void thread_2(void* param) {
    while (1) {
        x = 0; // x is global.
        usleep(20000);
    }
}

如何暂停第二个线程的执行,等待第一个线程执行完毕,然后安全地在第二个线程中继续执行,以防止出现竞争条件?

你需要添加 mutex.When 一个互斥锁尝试 运行 在一个关键区域,另一个必须等​​待 so.Create 一个停止线程的互斥锁

pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  consum = PTHREAD_COND_INITIALIZER;

void function(){ //were the mutex is trying to run 
 pthread_mutex_lock(&lock);
 pthrad_cond_wait(&consum,lock);// this is saying  that : only one at a time
 
  //critical area


  //here you can use signals to let the other threads when this current thread is funish.
  pthread_mutex_unlock(&lock);// when a thread unlock's the  mutex then the other starting to run the critical area

}

如果你想创建线程,例如 6 个线程,你不需要像你那样使用 6 个函数,void thread 1 和 thread2.you 必须像这样创建它们:

pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;   // this locks the critical arrea
pthread_cond_t  consum = PTHREAD_COND_INITIALIZER; // and this is a conditional variable
    pthread_t consumerN[2];
    
    //then in your main function 
    int main(){
           
          
          pthread_create(&consumerN[1],NULL,thread_1,NULL);// go to thread_1
          pthread_create(&consumerN[2],NULL,thread_2,NULL);//go to thread_2
           
    }
    void thread_1(int *param){
       pthread_mutex_lock(&lock);
       pthread_cond_wait(&consum,lock);
       for (int i=0; i<10; i++) {
           x += i; // x is global.
      }
      pthread_mutex_unlock(&lock);
   }
   void thread_2(int *param){
       pthread_mutex_lock(&lock);
       pthread_cond_wait(&consum,lock);
       
      while(1){
          x=0;
          sleep(2000);


      }
      pthread_mutex_unlock(&lock);
  }