Linux 条件变量 pthread_cond_signal及pthread_cond_wait
Linux 条件变量 pthread_cond_signal及pthread_cond_wait
romalin99 发表于6年前
Linux 条件变量 pthread_cond_signal及pthread_cond_wait
  • 发表于 6年前
  • 阅读 218
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云实验室 1小时搭建人工智能应用,让技术更容易入门 免费体验 >>>   

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*静态初始化*/
pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;  //init cond

void *thread1(void*);
void *thread2(void*);
int i = 1; //global

int main(int argc,char*  argv[])
{
    pthread_t t_a;
    pthread_t t_b;//two thread

        pthread_create(&t_b,NULL,thread2,(void*)NULL);//Create thread
    pthread_create(&t_a,NULL,thread1,(void*)NULL);

    pthread_join(t_b,NULL);//wait a_b thread end
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    exit(0);
}
//t_a  实现线程t_b打印9以内3的倍数
void *thread1(void *junk){
    for(i = 1;i<= 9; i++){
        pthread_mutex_lock(&mutex); //互斥锁
        printf("call thread1 \n");
        if(i%3 == 0)
            pthread_cond_signal(&cond); //send sianal to t_b
        else
            printf("thread1: %d\n",i);
        pthread_mutex_unlock(&mutex);
        printf("1  [%d]\n",i);
        sleep(1);
    }
}
//t-b  打印其他的数   
void *thread2(void*junk){
    while(i < 9)
    {
        pthread_mutex_lock(&mutex);//开始进入临界区
        printf("call thread2 \n");
        if(i%3 != 0)//操作有2步,是原子操作。第一解锁,先解除之前的pthread_mutex_lock锁定的mutex;第二 挂起,阻塞并在等待队列里休眠,即所在线程挂起,直到再次被再次唤醒,唤醒的条件是由pthread_cond_signal(&cond);发出的cond信号来唤醒。
            pthread_cond_wait(&cond,&mutex); //wait 必须和互斥锁同时用在一个线程里,它同时起到对资源的加锁和解锁
        printf("thread2: %d\n",i);
        pthread_mutex_unlock(&mutex);//离开临界区
        printf("2 ....\n"  );
        sleep(1);
    }

}

*********************************************************************

int __pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)

pthread_cond_wait 源码

{
  volatile pthread_descr self = thread_self();
  pthread_extricate_if extr;
  int already_canceled = 0;
  int spurious_wakeup_count;

  /* Check whether the mutex is locked and owned by this thread.  */
  if (mutex->__m_kind != PTHREAD_MUTEX_TIMED_NP
      && mutex->__m_kind != PTHREAD_MUTEX_ADAPTIVE_NP
      && mutex->__m_owner != self)
    return EINVAL;

  /* Set up extrication interface */
  extr.pu_object = cond;
  extr.pu_extricate_func = cond_extricate_func;

  /* Register extrication interface */
  THREAD_SETMEM(self, p_condvar_avail, 0);
  __pthread_set_own_extricate_if(self, &extr);

  /* Atomically enqueue thread for waiting, but only if it is not
     canceled. If the thread is canceled, then it will fall through the
     suspend call below, and then call pthread_exit without
     having to worry about whether it is still on the condition variable queue.
     This depends on pthread_cancel setting p_canceled before calling the
     extricate function. */

  __pthread_lock(&cond->__c_lock, self);
  if (!(THREAD_GETMEM(self, p_canceled)
      && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE))
    enqueue(&cond->__c_waiting, self);
  else
    already_canceled = 1;
  __pthread_unlock(&cond->__c_lock);

  if (already_canceled) {
    __pthread_set_own_extricate_if(self, 0);
    __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
  }

  pthread_mutex_unlock(mutex);

  spurious_wakeup_count = 0;
  while (1)
    {
      suspend(self);
      if (THREAD_GETMEM(self, p_condvar_avail) == 0
      && (THREAD_GETMEM(self, p_woken_by_cancel) == 0
          || THREAD_GETMEM(self, p_cancelstate) != PTHREAD_CANCEL_ENABLE))
    {
      /* Count resumes that don't belong to us. */
      spurious_wakeup_count++;
      continue;
    }
      break;
    }

  __pthread_set_own_extricate_if(self, 0);

  /* Check for cancellation again, to provide correct cancellation
     point behavior */

  if (THREAD_GETMEM(self, p_woken_by_cancel)
      && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
    THREAD_SETMEM(self, p_woken_by_cancel, 0);
    pthread_mutex_lock(mutex);
    __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
  }

  /* Put back any resumes we caught that don't belong to us. */
  while (spurious_wakeup_count--)
    restart(self);

  pthread_mutex_lock(mutex);
  return 0;
}

示例的解释: 
call thread2:是线程2即t_b首先上锁,即 pthread_mutex_lock(&mutex);锁住了mutex使得此进程执行线程2中的临界区的代码,当执行到45行:if(i%3 != 0),此时i=1,满足此条件,则执行46行: pthread_cond_wait(&cond,&mutex); 这句是关键,pthread_cond_wait(&cond,&mutex)操作有两步,是原子操作:第一 解锁,先解除之前的pthread_mutex_lock锁定的mutex;第二 挂起,阻塞并在等待对列里休眠,即线程2挂起,直到再次被唤醒,唤醒的条件是由pthread_cond_signal(&cond);发出的cond信号来唤醒。 

call thread1:由于pthread_cond_wait已经对线程2解锁,此时另外的线程只有线程1,那么线程1对mutex上锁,若这时有多个线程,那么线程间上锁的顺序和操作系统有关。 

thread1: 1:线程1上锁后执行临界区的代码,当执行到if(i%3 == 0)此时i=1,不满足条件,则pthread_cond_signal(&cond);不被执行,那么线程2仍处于挂起状态,输出thread1: 1后线程1由pthread_mutex_unlock(&mutex);解锁。 

thread1: 2:这时此进程中只有2个线程,线程2处于挂起状态,那么只有线程1,则线程1又对mutex上锁,此时同样执行临界区的代码,而且i=2,不满足条件,pthread_cond_signal(&cond);不被执行,那么线程2仍处于挂起状态,输出thread1: 1后线程1由pthread_mutex_unlock(&mutex);解锁。 

call thread1:同样由线程1上锁,但此时i=3,满足条件pthread_cond_signal(&cond)被执行,那么pthread_cond_signal(&cond)会发出信号,来唤醒处于挂起的线程2。 

thread2: 3:由于pthread_cond_signal唤醒了线程2,即i=3满足条件,pthread_cond_wait(&cond,&mutex);被执行,那么pthread_cond_wait(&cond,&mutex)此时也有一步操作:上锁;即对线程2上锁,此时的pthread_cond_wait(&cond,&mutex)的操作相当与pthread_mutex_lock(&mutex);那么线程2继续执行上锁后的临界区的代码,并由pthread_mutex_unlock(&mutex);对线程2进行解锁。 

.......


共有 人打赏支持
粉丝 8
博文 26
码字总数 76769
×
romalin99
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: