原创 使用pthread_cond_timedwait把一个线程作为一个定时器使用.

本文介绍了一个使用pthread库创建线程并实现定时等待的例子。主线程创建一个子线程,在子线程中初始化互斥锁和条件变量,并设置超时时间为3秒。循环中通过条件变量的带超时选项的等待,演示了如何处理超时情况。

//http://blog.csdn.net/lllxy/archive/2009/02/10/3874415.aspx

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void * Proc(void * arg)
{
   pthread_cond_t cond;
   pthread_mutex_t mutex;

    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);

   timespec to;

    int i = 0;
    pthread_mutex_lock(&mutex);
    to.tv_sec = time(NULL) + 3;
    to.tv_nsec = 0;
    while (i < 5)
    {

        int err = pthread_cond_timedwait(&cond, &mutex, &to);
        if (err == ETIMEDOUT)
        {
             printf("time out %d: dispatch something.../n",i);
         i++;
        }

    }

     pthread_mutex_unlock(&mutex);


}
int main()
{   
    pthread_t pid;
    int i=0;
    printf("create thread.../n");
    pthread_create(&pid,0,Proc,0);
    pthread_join(pid,NULL);
    sleep(1);
    printf("Succeed exit!/n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值