#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int gval = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *func1_th(void *arg)
{
pthread_mutex_lock(&mutex);
if (5 != gval) {
printf("=======%s->%d===thread 1 wait start!====\n", __func__, __LINE__);
pthread_cond_wait(&cond, &mutex);
}
/**
* do something here
*/
printf("=======%s->%d====thread 1 do something!===\n", __func__, __LINE__);
pthread_mutex_unlock(&mutex);
return NULL;
}
#if 0
void *func1_th(void *arg)
{
//for (;;) {
sleep(2);
pthread_mutex_lock(&mutex);
/*
printf("=======%s->%d=======\n", __func__, __LINE__);
if (5 != gval) {
pthread_mutex_unlock(&mutex);
return NULL;
}
*/
/**
* do something here
*/
printf("=======%s->%d====thread 1 do something!===\n", __func__, __LINE__);
//}
return NULL;
}
#endif
void *func2_th(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
for (i = 0; i < 10; i++) {
printf("=======%s->%d=======\n", __func__, __LINE__);
sleep(1);
gval++;
if (5 == gval) {
pthread_cond_signal(&cond);
printf("=======%s->%d===signal====\n", __func__, __LINE__);
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t tid1, tid2;
if (0 != pthread_create(&tid1, NULL, func1_th, NULL)) {
printf("pthread_create failed!\n");
return -1;
}
sleep(1);
if (0 != pthread_create(&tid2, NULL, func2_th, NULL)) {
printf("pthread_create failed!\n");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
2_pthread_sync.tgz
需积分: 10 185 浏览量
2014-12-20
13:57:23
上传
评论
收藏 1KB TGZ 举报
shallnet
- 粉丝: 553
- 资源: 30
最新资源
- 冯璐阳 42105650—祝福.docx
- 基于多种算法及改进算法实现的移动机器人路径规划matlab源码(含A星算法+PRM+RRT的改进等).zip
- 布里斯托尔纸细分市场、总体规模、先进性、市占率行业分析报告2024年.docx
- Obi绳子插件,好用的很 6.5.4版本
- openjfx-22.0.1-windows-x64-bin-sdk.zip
- 基于ros和stm32f1的小车代码(含串口通信)+项目说明.zip
- 人体姿态估计-基于Tensorflow实现的人体姿态估计算法-附项目源码-优质项目分享.zip
- java实现所有算法大全
- JDBC DAO模式 (复习)
- Proteus仿真AT89C51电子密码锁
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈