C/C++ pthread_cond_timedwait()函数使用心得
来源:互联网 发布:腾讯红包大数据,归属地 编辑:程序博客网 时间:2024/05/24 03:45
由于工作上的事情,要用到线程之间的同步,而且有超时处理,在网上看到了使用pthread_cond_timedwait()函数和pthread_cond_wait()函数,其实2个函数都差不多,我主要是要用pthread_cond_timedwait()函数。
pthread_cond_timedwait()函数有三个入口参数:
(1)pthread_cond_t __cond:条件变量(触发条件)
(2)pthread_mutex_t __mutex: 互斥锁
(3)struct timespec __abstime: 等待时间(其值为系统时间 + 等待时间)
当在指定时间内有信号传过来时,pthread_cond_timedwait()返回0,否则返回一个非0数(我没有找到返回值的定义);
在使用pthread_cond_timedwait()函数时,必须有三步:
1:加互斥锁:pthread_mutex_lock(&__mutex)
2:等待:pthread_cond_timedwait(&__cond, &__mutex, &__abstime) //解锁->等待->加锁
3:解互斥锁:pthread_mutex_unlock(&__mutex)
发送信号量时,也要有三步:
1:加互斥锁:pthread_mutex_lock(&__mutex)
2:发送:pthread_cond_signal(&__cond)
3:解互斥锁:pthread_mutex_unlock(&__mutex)
那么,这里就有一个问题,等待的时候已经加上锁了,那么我发送的时候怎么才能运行到发送函数呢?其实这是因为在pthread_cond_timedwait()函数中已经对互斥锁进行解锁操作了,所以这个时候发送信号量是不会阻塞的。其实仔细想想,这样不是才能保证同步吗?(写完代码后考虑一下)
#include <stdio.h>#include <pthread.h>#include <string.h>#include <unistd.h>#include <semaphore.h>#include <sys/time.h>#define SENDSIGTIME 10pthread_cond_t g_cond;pthread_mutex_t g_mutex;void thread1(void *arg){ int inArg = (int)arg; int ret = 0; struct timeval now; struct timespec outtime; pthread_mutex_lock(&g_mutex); gettimeofday(&now, NULL); outtime.tv_sec = now.tv_sec + 5; outtime.tv_nsec = now.tv_usec * 1000; ret = pthread_cond_timedwait(&g_cond, &g_mutex, &outtime); //ret = pthread_cond_wait(&g_cond, &g_mutex); pthread_mutex_unlock(&g_mutex); printf("thread 1 ret: %d\n", ret);}int main(void){ pthread_t id1; int ret; pthread_cond_init(&g_cond, NULL); pthread_mutex_init(&g_mutex, NULL); ret = pthread_create(&id1, NULL, (void *)thread1, (void *)1); if (0 != ret) {printf("thread 1 create failed!\n");return 1; } printf("等待%ds发送信号!\n", SENDSIGTIME); sleep(SENDSIGTIME); printf("正在发送信号....\n"); pthread_mutex_lock(&g_mutex); pthread_cond_signal(&g_cond); pthread_mutex_unlock(&g_mutex); pthread_join(id1, NULL); pthread_cond_destroy(&g_cond); pthread_mutex_destroy(&g_mutex); return 0;}
- C/C++ pthread_cond_timedwait()函数使用心得
- C语言 clock() 函数使用心得
- UltraWinGrid使用心得(C#)
- C#--BackgroundWorker使用心得
- UltraWinGrid使用心得(C#)
- C/C++:pthread_cond_timedwait阻塞失败(立刻超时返回)
- Python C API 使用心得
- axis2/c初次使用心得
- Python C API 使用心得
- c/c++ const使用心得
- Python C API 使用心得
- pthread_cond_wait/pthread_cond_timedwait使用注意
- .c心得
- C 中scanf ( ) 函数用法 心得
- C 中scanf ( ) 函数用法 心得
- C 中scanf ( ) 函数用法 心得
- C 中scanf ( ) 函数用法 心得
- Objective-c 使用c函数
- day05 UART实战、源码阅读工具(Sourceinsight/Ctags)、Makefile编写
- day04 UART协议
- 高效能人士的七个习惯总结
- Java去除一个Map中value值最小的K个记录
- 高PowerSurfacing RE v2.4-4.1 for SolidWorks 2012-2017 Win64 6CD
- C/C++ pthread_cond_timedwait()函数使用心得
- day06 链接脚本、shell程序优化、IIC总线
- 阿里云数加产品家族图首次亮相
- LintCode 431 Connected Component in Undirected Graph
- 如何选择一个适合自己的专业
- [SVN] 分支同步、合入主干操作分享
- oninput事件
- mysql安装配置
- 静态代码块的使用(code)