探究点:
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:被阻塞的线程再次运行后,是从被阻塞的位置开始运行的。以上是个人实验总结,不足之处欢迎大家补充