使用pthread_cond_timedwait打印指定的时间

时间:2011-12-01 01:07:53

标签: c time pthreads mutex waithandle

嘿,我有一个与pthread_cond_timedwait相关的小问题。我已经尝试将它实现到这段代码中。我不能把争论时间正确,因为我不太确定我在做什么。如果有人能指出我正确的方向,那将非常感激!

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

pthread_mutex_t timeLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;

int timeIndex = 0;
time_t times[100];

void print_time(time_t tt)
{
    char buf[80];
    struct tm* st = localtime(&tt);
    strftime(buf, 80, "%c", st);

    printf("Call me on: ");
    printf("%s\n", buf);
}

void *add_time(time_t tt){
    if(timeIndex == 100)
        timeIndex = 0;

    struct timespec ts;
    times[timeIndex] = tt;
    timeIndex++;

    ts.tv_sec = tt;
    print_time(tt); // print element
}

void * call_time()
{
    while(1)
    {
        const time_t c_time = time(NULL);
        int i;
        for(i = 0; i <= 100; i++)
        {
            if(c_time == times[i])
            {
                printf("\nWake me up!\n");
                times[i] = 0;
            }
        }   
    }

}

void * newTime()
{
        while(1)
        {
            time_t f_time;

            f_time = time(NULL); 

            srand ( time(NULL) );
            f_time += rand()%100;

            add_time(f_time);
            sleep(1);
        }
}

int main(void)
{
        pthread_t timeMet;
        pthread_t time;

        pthread_create(&time, NULL, newTime, NULL);
        pthread_create(&timeMet, NULL, call_time, NULL);

        pthread_join(time, NULL);
        pthread_join(timeMet, NULL);
        return 0;
}

0 个答案:

没有答案