pthread_count_t与pthread_mutex_t的运用

 

编译:

[X61@horizon threads]$ gcc thread_cond.c -lpthread -o tcd

下面是程序执行结果:

[X61@horizon threads]$ ./tcd
thread1: lock 30
thread1: unlock 40

thread2: lock 52
thread2: wait 1 55
thread1: lock 30
thread1: unlock 40

thread1: lock 30
thread1:signal 1 33
thread1:signal 2 35
thread1: unlock 40

thread2: wait 2 57
thread2: unlock 61

thread1: lock 30
thread1: unlock 40

thread2: lock 52
thread2: wait 1 55
thread1: lock 30
thread1: unlock 40

thread1: lock 30
thread1:signal 1 33
thread1:signal 2 35
thread1: unlock 40

thread2: wait 2 57
thread2: unlock 61

这里的两个关键函数就在pthread_cond_wait和pthread_cond_signal函数。

本例中:

线程一先运行,获得mutex锁,打印,然后释放mutex锁。然后堵塞自己1秒。



线程二此时和线程一应该是并发的运行
,这里是一个要点。为什么说是线程此时是并发的运行。由于此时不做不论什么干涉的话。是没有办法确定是线程一先获得运行还是线程二先获得运行,究竟那个线程先获得运行。取决于操作系统的调度,想刻意的让线程2先运行。能够让线程2一出来。先sleep一秒。
这里并发运行的情况是,线程一先进入循环,然后获得锁。此时预计线程二运行,堵塞在
pthread_mutex_lock(&mutex);
这行语句中,直到线程1释放mutex锁
pthread_mutex_unlock(&mutex);/*解锁相互排斥量*/
然后线程二得已运行。获取metux锁,满足if条件,到pthread_cond_wait (&cond,&mutex);/*等待*/
这里的线程二堵塞,不不过等待cond变量发生改变。同一时候释放mutex锁 (这里wait的时候会释放mutex。而一旦接收到信号(且其他线程解锁mutex)退出的时候会又一次给mutex加锁。实际上,线程信号与线程锁依赖,详见下篇)
mutex锁释放后,线程1最终获得了mutex锁。得已继续执行,当线程1的if(i%3==0)的条件满足后,通过pthread_cond_signal发送信号,告诉等待cond的变量的线程(这个情景中是线程二)。cond条件变量已经发生了改变。

只是此时线程二并没有马上得到执行 ,由于线程二还在等待mutex锁的释放,所以线程一继续往下走,直到线程一释放mutex锁。线程二才干停止等待,打印语句,然后往下走通过pthread_mutex_unlock(&mutex)释放mutex锁。进入下一个循环。

posted @ 2017-05-10 15:38  jzdwajue  阅读(178)  评论(0编辑  收藏  举报