睡在一个线程(C / POSIX线程) [英] Sleeping in a Thread (C / POSIX Threads)
问题描述
我开发多线程应用程序,使得使用的 POSIX线程。我使用的线程做的期刊的工作,并为此目的,我使用 usleep(3)挂起线程执行。我的问题是如何从主线程取消usleep()函式定时器,我试过 pthread_kill(螺纹,SIGALRM)
但它导致主终止全局效果应用程序(默认)。这里是我的伪code:
I am developing a multithreaded application that makes use of POSIX Threads. I am using threads for doing a periodical job and for that purpose I am using usleep(3) to suspend thread execution. My question is how can I cancel usleep() timer from the main thread, I tried pthread_kill(thread, SIGALRM)
but it has a global effect which results in termination of the main application (by default). Here is my pseudo code:
void threaded_task(void *ptr) {
initialize();
while(running) {
do_the_work();
usleep(some_interval);
}
clean_up();
release_resources();
}
这是从主线程定线程用于停止(和正常关闭)伪函数
And here is the pseudo function that is used to stop (and gracefully shutdown) given thread from the main thread:
void stop_thread(pthread_t thread) {
set_running_state(thread, 0); // Actually I use mutex staff
// TODO: Cancel sleep timer so that I will not wait for nothing.
// Wait for task to finish possibly running work and clean up
pthread_join(thread, NULL);
}
什么是便捷的方式来实现我的目标?我一定要使用条件变量或我可以做到使用睡眠()这个变种?
What is the convenient way to achieve my goal? Do I have to use conditional variables or can I do this using sleep() variants?
推荐答案
使用选择()
与FIFO或插座,你可以以唤醒它戳。
USe select()
with a FIFO or socket that you can poke in order to wake it up.
这篇关于睡在一个线程(C / POSIX线程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!