Linux中,C:终止multple线程在几秒钟后(计时器?) [英] Linux, C: terminate multple threads after some seconds (timer?)
问题描述
的Linux,C。
我创建多个线程运行的工作负载,我想这些信号线程停止/指定秒/次出来后终止。
我如何用C实现这一点?
Linux, C. I created multiple threads to run workloads, and I want to signal those threads to stop/terminate after a specified seconds/time out. How do I implement this by C?
void *do_function(void *ptr)
{
//calculating, dothe workload here;
}
int run(struct calculate_node *node)
{
pthread_t threads[MAX_NUM_THREADS];
for (t = 0; t < node->max_threads; t++) {
rc = pthread_create(&threads[t], NULL, do_function, (void*)node);
if(rc) return -1;
}
//how do I create timer here to fire to signal those threads to exit after specified seconds?
for (t = 0; t < node->max_threads; t++) {
pthread_join(threads[t], NULL);
}
free(threads);
}
谢谢!
推荐答案
不知道是否有创建一个定时事件可移植的方法,但如果主
没有还有别的事做,它可以简单地调用睡眠
浪费时间。
Not sure if there's a portable way to create a timer event, but if main
doesn't have anything else to do, it could simply call sleep
to waste time.
至于信号线程,你有两个选择:合作或者终止非合作终止。随着合作终止后,线程必须定期检查标志,看它是否应该终止。随着非合作终止后,你叫 pthread_cancel可以
来结束线程。 (有关可用于优雅地结束线程附加功能信息,请参阅 pthread_cancel可以
的手册页。)
As for signaling the threads, you have two choices: cooperative termination or non-cooperative termination. With cooperative termination, the thread must periodically check a flag to see if it's supposed to terminate. With non-cooperative termination, you call pthread_cancel
to end the thread. (See the man page for pthread_cancel
for information about additional functions that can be used to gracefully end the thread.)
我觉得合作的终止更容易实现。这里有一个例子:
I find cooperative termination easier to implement. Here's an example:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static int QuitFlag = 0;
static pthread_mutex_t QuitMutex = PTHREAD_MUTEX_INITIALIZER;
void setQuitFlag( void )
{
pthread_mutex_lock( &QuitMutex );
QuitFlag = 1;
pthread_mutex_unlock( &QuitMutex );
}
int shouldQuit( void )
{
int temp;
pthread_mutex_lock( &QuitMutex );
temp = QuitFlag;
pthread_mutex_unlock( &QuitMutex );
return temp;
}
void *somefunc( void *arg )
{
while ( !shouldQuit() )
{
fprintf( stderr, "still running...\n");
sleep( 2 );
}
fprintf( stderr, "quitting now...\n" );
return( NULL );
}
int main( void )
{
pthread_t threadID;
if ( pthread_create( &threadID, NULL, somefunc, NULL) != 0 )
{
perror( "create" );
return 1;
}
sleep( 5 );
setQuitFlag();
pthread_join( threadID, NULL );
fprintf( stderr, "end of main\n" );
}
这篇关于Linux中,C:终止multple线程在几秒钟后(计时器?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!