#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static pthread_mutex_t m_lock;
static pthread_cond_t m_worker_cond;
static pthread_t pthread_a;
static pthread_t pthread_b;
int i=1;
void *thread1(void *junk)
{
for(i=1;i<=6;i++)
{
pthread_mutex_lock(&m_lock);
printf("thread1: lock %d\n", __LINE__);
if(i%3==0){
printf("thread1:signal 1 %d\n", __LINE__);
pthread_cond_signal(&m_worker_cond);
printf("thread1:signal 2 %d\n", __LINE__);
sleep(1);
}
pthread_mutex_unlock(&m_lock);
printf("thread1: unlock %d\n", __LINE__);
sleep(1);
}
}
void *thread2(void *junk)
{
while(i<6)
{
pthread_mutex_lock(&m_lock);
printf("thread2: lock %d\n", __LINE__);
if(i%3!=0){
printf("thread2: wait 1 %d\n", __LINE__);
pthread_cond_wait(&m_worker_cond,&m_lock);
printf("thread2: wait 2 %d\n", __LINE__);
}
pthread_mutex_unlock(&m_lock);
printf("thread2: unlock %d\n", __LINE__);
sleep(1);
}
}
int main(int argc,char **argv)
{
pthread_cond_init(&m_worker_cond, NULL);
pthread_mutex_init(&m_lock, NULL);
pthread_create(&pthread_a,NULL,thread1,(void *)NULL);
pthread_create(&pthread_b,NULL,thread2,(void *)NULL);
pthread_join(pthread_a, NULL);
pthread_join(pthread_b, NULL);
pthread_mutex_destroy(&m_lock);
pthread_cond_destroy(&m_worker_cond);
return 0;
}
编译脚本 Makefile 如下:
make:
gcc -o pthread pthread.c -lpthread
clean:
rm -rf *.o
运行结果:
zhangtiangui@silead-fp:~/my_test_code$ ./pthread
thread1: lock 16
thread1: unlock 24
thread2: lock 33
thread2: wait 1 35
thread1: lock 16
thread1: unlock 24
thread1: lock 16
thread1:signal 1 18
thread1:signal 2 20
thread1: unlock 24
thread2: wait 2 37
thread2: unlock 40
thread1: lock 16
thread1: unlock 24
thread2: lock 33
thread2: wait 1 35
thread1: lock 16
thread1: unlock 24
thread1: lock 16
thread1:signal 1 18
thread1:signal 2 20
thread1: unlock 24
thread2: wait 2 37
thread2: unlock 40
详解:
-
主函数 main 创建并执行两个线程:
pthread_create(&pthread_a,NULL,thread1,(void *)NULL);//线程pthread_a
pthread_create(&pthread_b,NULL,thread2,(void *)NULL);//线程pthread_b -
线程pthread_a操作函数thread1:
void *thread1(void *junk)
{
for(i=1;i<=6;i++)
{
pthread_mutex_lock(&m_lock);
printf(“thread1: lock %d\n”, LINE);
if(i%3==0){
printf(“thread1:signal 1 %d\n”, LINE);
pthread_cond_signal(&m_worker_cond);
printf(“thread1:signal 2 %d\n”, LINE);
sleep(1);
}
pthread_mutex_unlock(&m_lock);
printf(“thread1: unlock %d\n”, LINE);
sleep(1);
}
}
获得互斥锁,进锁/出锁,sleep(1);延时; -
线程pthread_b操作函数thread2:
void *thread2(void *junk)
{
while(i<6)
{
pthread_mutex_lock(&m_lock);
printf(“thread2: lock %d\n”, LINE);
if(i%3!=0){
printf(“thread2: wait 1 %d\n”, LINE);
pthread_cond_wait(&m_worker_cond,&m_lock);
printf(“thread2: wait 2 %d\n”, LINE);
}
pthread_mutex_unlock(&m_lock);
printf(“thread2: unlock %d\n”, LINE);
sleep(1);
}
}
获得互斥锁,进锁/出锁,
pthread_cond_wait(&m_worker_cond,&m_lock);
这是出锁,堵塞等待条件量变化后唤醒 -
唤醒:
thread1函数中if(i%3==0)为真时,pthread_cond_signal(&m_worker_cond);唤醒等待的堵塞,注意这里必须先出锁后才能唤醒堵塞等待(pthread_cond_wait(&m_worker_cond,&m_lock)😉;
5 执行堵塞等待:
pthread_cond_wait(&m_worker_cond,&m_lock);//唤醒并往下执行代码。