C语言pthread_cond_wait和pthread_cond_signal简单探究

探究点:
1:pthread_cond_signal唤醒使用pthread_cond_wait进行阻塞的线程时,被唤醒的线程是否一定会马上执行。
2:使用pthread_cond_wait进行阻塞的线程被唤醒并运行后是否会对当前线程加锁

代码

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

pthread_mutex_t mutex;
pthread_cond_t cond;
int iCount = 0;

void * thread1(void* arg)
{
  while(1)
  {
      printf("Enter thread 1\n");  //进入线程1
      pthread_mutex_lock(&mutex);
      iCount++;
      printf("%d\n",iCount);
      if(iCount >= 100)
      {
        pthread_cond_signal(&cond);  //唤醒线程2
        printf("Wake up thread 2\n");  
      }
      pthread_mutex_unlock(&mutex);
   }         
}

void * thread2(void* arg)
{
  while(1)
  {
      printf("Enter thread 2\n");  //进入线程2
      pthread_mutex_lock(&mutex);
      while(iCount < 100)  //用while不用if的原因:避免“惊群效应”
      { 
        pthread_cond_wait(&cond, &mutex);
        printf("Thread 2 is woken up and running\n");  //线程2被唤醒并执行
        int i = 0;
        while(i <= 100)
        {
          printf("Always in thread 2 and i = %d\n",i);  //一直执行线程2
          i++;
        }
      }
      printf("iCount >= 100\r\n");
      iCount = 0;
      pthread_mutex_unlock(&mutex);
  }
}

int main(){
  pthread_t tid1,tid2;
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond,NULL);
  pthread_create(&tid1,NULL,thread1,NULL);
  pthread_create(&tid2,NULL,thread2,NULL);
  sleep(2);
  return 0;
}

根据运行结果进行探究
对于探究点1:
在这里插入图片描述
可以看到:当 iCount 等于100的时候进行了唤醒线程2的操作,但是线程2并没有马上执行,而是在 iCount 增加到102的时候才执行的。我们知道,当一个线程从阻塞状态被唤醒时,会进入到就绪状态而不是马上进入到运行状态,在这个场景也适用。

对于探究点2:
在这里插入图片描述
可以看到,当线程二被唤醒后,在他没有释放线程锁之前,一直都是在运行线程2中的代码,意味着线程1无法获得锁,所以我们可以猜测,pthread_cond_wait被唤醒并运行的同时,会拿到线程锁,尽管没有通过pthread_mutex_lock显式调用。

结论:
1:pthread_cond_signal唤醒使用pthread_cond_wait进行阻塞的线程时,被唤醒的线程不一定会马上执行
2:使用pthread_cond_wait进行阻塞的线程被唤醒并运行后会对当前线程加锁
ps:被阻塞的线程再次运行后,是从被阻塞的位置开始运行的。以上是个人实验总结,不足之处欢迎大家补充

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值