gpt4 book ai didi

c - Linux, C : terminate multple threads after some seconds (timer? )

转载 作者:IT王子 更新时间:2023-10-29 01:08:22 24 4
gpt4 key购买 nike

Linux,C.我创建了多个线程来运行工作负载,我想在指定的秒数/超时后通知这些线程停止/终止。我如何用 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);
}

谢谢!

最佳答案

不确定是否有一种可移植的方法来创建计时器事件,但是如果 main 没有任何其他事情要做,它可以简单地调用 sleep 来浪费时间.

至于向线程发送信号,您有两种选择:合作终止或非合作终止。对于协作终止,线程必须定期检查标志以查看它是否应该终止。对于非合作终止,您可以调用 pthread_cancel 来结束线程。 (有关可用于正常结束线程的附加函数的信息,请参阅 pthread_cancel 的手册页。)

我发现合作终止更容易实现。这是一个例子:

#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" );
}

关于c - Linux, C : terminate multple threads after some seconds (timer? ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32079899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com