pthread_cond_timedwait按相对时间等待超时完整示例代码

pthread_cond_timedwait()在官方文档中介绍了按绝对时间等待超时,但是几乎没有对按相对等待做说明。然而绝对时间模式有个最致命的缺点,就是在设置等待时间的时候,若系统时间发生了调整,可能出现永远等不到超时的极端情况。使用相对时间可以避免上述问题。

下面给出一段示例代码说明如何使pthread_cond_timedwait按相对时间等待超时,其中最关键的一点就是使用pthread_condattr_setclock设置pthread_cond_timedwait成相对时间模式:

 

#include <stdio.h>
#include <pthread.h>
#include <time.h>

typedef struct mutex_cond
{
		pthread_condattr_t cattr;
        pthread_mutex_t i_mutex;
        pthread_cond_t i_cv;
		void* i_sigevent; 
}mutex_cond_t;

// g++ -o pwait pwait.cpp -lpthread -lrt
int main()
{
	mutex_cond_t mcond;
	int ret = pthread_condattr_init(&(mcond.cattr));
	if (ret != 0)
	{
		return (1);
	}
	mcond.i_sigevent = NULL;
    ret = pthread_mutex_init ( &(mcond.i_mutex), NULL);
	ret = pthread_condattr_setclock(&(mcond.cattr), CLOCK_MONOTONIC);
	ret = pthread_cond_init(&(mcond.i_cv), &(mcond.cattr));

	struct timespec tv;
	while(1)
	{
		clock_gettime(CLOCK_MONOTONIC, &tv);
		printf("now time:%d\n", tv.tv_sec);
		tv.tv_sec += 20;// 设置20秒后没收到事件超时返回
		ret = pthread_cond_timedwait(&(mcond.i_cv), &(mcond.i_mutex), &tv);
	}
	
	return 0;
}


 

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个使用 pthread_cond_timedwait 的简单示例: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void* thread_func(void* arg) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 5; // 设置等待时间为5秒 pthread_mutex_lock(&mutex); int ret = pthread_cond_timedwait(&cond, &mutex, &ts); if (ret == 0) { printf("Thread woke up before timeout.\n"); } else if (ret == ETIMEDOUT) { printf("Thread timed out.\n"); } else { printf("Error waiting on condition variable.\n"); } pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); // 做一些其他的工作 pthread_cond_signal(&cond); // 唤醒等待线程 pthread_join(thread, NULL); return 0; } ``` 在上面的示例中,主线程创建了一个新线程,然后做一些其他的工作。在等待线程函数中,它使用 clock_gettime 来获取当前时间,并在当前时间的基础上增加5秒,表示等待超时时间。然后调用 pthread_cond_timedwait 函数等待条件变量的信号,如果在超时之前收到信号,则会打印 "Thread woke up before timeout.",如果超时,则会打印 "Thread timed out."。 在主线程中,我们调用 pthread_cond_signal 函数来唤醒等待线程。最后,我们使用 pthread_join 等待子线程结束。 请注意,这只是一个简单的示例,实际使用时需要根据具体的需求进行适当的修改和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值