2016年12月16日 17:34:48
这两天开始看linux下的线程编程,看到了关于互斥锁这一块儿,写了一个小实例如下
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t mutex;
void *function(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0;i<3;i++)
{
printf("1\n");
//sleep(1);
}
}
void *function1(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0;i<3;i++)
{
printf("2\n");
//sleep(1);
}
}
void *function2(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0;i<3;i++)
{
printf("3\n");
//sleep(1);
}
}
int main(void)
{
pthread_t pthread_no,pthread_no1,pthread_no2;
pthread_mutex_init(&mutex,NULL);
pthread_create(&pthread_no,NULL,function,NULL);
pthread_create(&pthread_no1,NULL,function1,NULL);
pthread_create(&pthread_no2,NULL,function2,NULL);
pthread_join(pthread_no,NULL);
pthread_mutex_unlock(&mutex);
pthread_join(pthread_no1,NULL);
pthread_mutex_unlock(&mutex);
pthread_join(pthread_no2,NULL);
pthread_mutex_unlock(&mutex);
return 0;
}
但是偶尔结果也会是这样子的
就被挂起了,不执行向下的操作了。
最后想来了问题所在:
输出1的那个线程如果先执行,输出2的线程接下来执行,输出3的线程最后执行。那么到了pthread_join()代码段时,就正常执行了。
可是万一执行顺序不是上述顺序,那么执行完毕实际执行的第一个线程之后,主线程在等待第一个线程结束,一直在阻塞主线程等待,所以互斥锁也没有解锁,既然互斥锁没有被解锁,那么其他线程就会一直被挂起,形成死锁。
还有个问题,关于pthread_join()一开始我以为是启动了系统的某个线程使用轮询方式在一直查询他自己所等待的线程是否运行完毕。后来这个问题出现之后,感觉它的机制不是这样子的,上网查了一下之后,说是比如:
pthread_join(pthread_no,NULL);
pthread_join(pthread_no1,NULL);
pthread_join(pthread_no2,NULL);
它的机制实际上是主线程一直在等待no线程结束,no未完成时不去理会其它的线程状态,那么这样子的话也就能解释通了。