69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//初始化互斥锁
pthread_cond_t cond =PTHREAD_COND_INITIALIZER;//初始化条件变量
void func_pthread1(void)
{
// thread1 is running
printf("Thread1 start to execute!\n");
//pthread_mutex_lock(&mutex);//加锁
// wait a condition here, thread will be blocked
printf("Thread1 will be blocked and wait the signal\n");
pthread_cond_wait(&cond,&mutex);// 设置条件变量,等待SIGNAL
while(1)
{
printf("Thread1 have received the signal\n");
printf("Thread1 will be blocked and wait the signal\n");
pthread_cond_wait(&cond,&mutex);// 设置条件变量,等待SIGNAL
}
//sleep(1);
//pthread_mutex_unlock(&mutex);//解锁
pthread_exit(0);
}
void func_pthread2(void)
{
int i = 0;
sleep(1);
//pthread_mutex_lock(&mutex);//加锁
printf("hello, thread2 start to execute\n");
//pthread_mutex_unlock(&mutex);//解锁
while (i++ < 3)
{
printf("Thread2 send a signal to thread1\n");
pthread_cond_signal(&cond); //发送SIGNAL
sleep(3);
}
}
int main()
{
pthread_t pthread1,pthread2;
pthread_create(&pthread1,NULL,(void *)func_pthread1,NULL);//创建线程pthread1
pthread_create(&pthread2,NULL,(void *)func_pthread2,NULL);//创建线程pthread2
pthread_join(pthread1,NULL);
pthread_join(pthread2,NULL);
}