pthread_cond_timedwait的使用例子
时间: 2023-08-12 22:05:44 浏览: 42
下面是一个使用pthread_cond_timedwait函数的例子:
```
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *thread_func(void *arg) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 2; // 等待2秒钟
pthread_mutex_lock(&mutex);
int ret = pthread_cond_timedwait(&cond, &mutex, &ts);
if (ret == 0) {
printf("Thread: signaled\n");
} else {
printf("Thread: timed out\n");
}
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread, NULL, thread_func, NULL);
sleep(1); // 等待1秒钟,确保新线程已经运行
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
在这个例子中,我们创建了一个新的线程,并在该线程中等待一个条件变量。我们使用pthread_cond_timedwait函数,在调用该函数时传递一个等待时间,如果在等待时间内条件变量被信号,则该函数返回0,否则返回ETIMEDOUT错误。在主线程中,我们在等待1秒钟后发送信号给条件变量。如果在2秒的等待时间内收到了信号,线程将输出“Thread: signaled”,否则将输出“Thread: timed out”。
需要注意的是,使用pthread_cond_timedwait函数时,必须先获取互斥锁,否则可能会出现竞争条件。