歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> linux條件鎖和互斥鎖

linux條件鎖和互斥鎖

日期:2017/2/25 10:37:58   编辑:Linux教程
 等待線程

  1。使用pthread_cond_wait前要先加鎖

  2。pthread_cond_wait內部會解鎖,然後等待條件變量被其它線程激活

  3。pthread_cond_wait被激活後會再自動加鎖

  激活線程:

  1。加鎖(和等待線程用同一個鎖)

  2。pthread_cond_signal發送信號

  3。解鎖

  激活線程的上面三個操作在運行時間上都在等待線程的pthread_cond_wait函數內部。

  程序示例:

  #include <stdio.h>

  #include <pthread.h>

  #include <unistd.h>

  pthread_mutex_t count_lock;

  pthread_cond_t count_nonzero;

  unsigned count = 0;

  void * decrement_count(void *arg) {

  pthread_mutex_lock (&count_lock);

  printf("decrement_count get count_lock\n");

  while(count==0) {

  printf("decrement_count count == 0 \n");

  printf("decrement_count before cond_wait \n");

  pthread_cond_wait( &count_nonzero, &count_lock);

  printf("decrement_count after cond_wait \n");

  }

  count = count -1;

  pthread_mutex_unlock (&count_lock);

  }

  void * increment_count(void *arg){

  pthread_mutex_lock(&count_lock);

  printf("increment_count get count_lock\n");

  if(count==0) {

  printf("increment_count before cond_signal\n");

  pthread_cond_signal(&count_nonzero);

  printf("increment_count after cond_signal\n");

  }

  count=count+1;

  pthread_mutex_unlock(&count_lock);

  }

  int main(void)

  {

  pthread_t tid1,tid2;

  pthread_mutex_init(&count_lock,NULL);

  pthread_cond_init(&count_nonzero,NULL);

  pthread_create(&tid1,NULL,decrement_count,NULL);

  sleep(2);

  pthread_create(&tid2,NULL,increment_count,NULL);

  sleep(10);

  pthread_exit(0);

  }

Copyright © Linux教程網 All Rights Reserved