c中的线程计时器

有人可以帮助我将我的代码转换为工作代码:

#include  #include  #include  #include  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* call back function - inform the user the time has expired */ void timeout_call_back() { printf("=== your time is up ===\n"); // doing some other stuff } /* Go to sleep for a period of seconds */ static void* start_timer(void *args) { /* function pointer */ void (*finish_function)(); int seconds = *((int*) args); pthread_mutex_lock(&mutex); // I want to do this action atomically printf("thread ID : %ld, go to sleep for %d\n", pthread_self(), seconds); finish_function = timeout_call_back; // ATOMIC PART // This function is called in real time, so I need it // to be safe, and it's executed just when the timer is not reached. atomic_function_callback(); // THIS IS MY PROBLEM. I WANT TO WAIT for (seconds) seconds, // but I don't want to block other threads. sleep(seconds); /* call the cb to inform the user time is out */ (*finish_function)(); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main() { pthread_t thread1, thread2, thread3; int seconds1 = 300; int seconds2 = 600; int seconds3 = 900; int rc1, rc2, rc3; rc1 = pthread_create(&thread1, NULL, start_timer, (void *) &seconds1); if(rc1) printf("=== Failed to create thread1\n"); rc2 = pthread_create(&thread2, NULL, start_timer, (void *) &seconds2); if(rc2) printf("=== Failed to create thread2\n"); rc3 = pthread_create(&thread3, NULL, start_timer, (void *) &seconds3); if(rc3) printf("=== Failed to create thread3\n"); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); printf("=== End of all threads in ===\n"); return 0; } 

当我运行此代码时,只有一个线程可以在一段时间内运行(导致互斥)但我需要这个互斥锁。 有什么替代睡眠()允许我做一个非阻塞计时器?

这只是一个样本,我的真实计时器很长(8小时)。

谢谢。

检查条件变量。 https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

你要做的是设置条件变量并为你的睡眠设置一个定时等待。 当您调用定时等待时,将为其他线程释放互斥锁。 当条件变量唤醒时,您将检查您的计时器是否已经过去并通知您的回调finish_function

你的问题有点模糊,但我想你想让所有三个线程同时处于hibernate状态,但是使用互斥锁来确保它们都不会同时运行finish函数?

如果是这种情况,那么您只想使用互斥锁来保护finish_function的调用,而不是保护睡眠。 然后每个线程将彼此hibernate,并且随着时间的推移,互斥锁将确保一次只有一个线程调用finish_function。

查看pthread_cond_timedwait