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

标签 c linux multithreading timer

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/

相关文章:

在 Mac 终端上使用命令行参数时发生 Java 服务器线程错误(Eclipse 文件)

c++ - 对 Vector 的多线程、只读访问。复制还是锁定?

c++ - 如何使用 BlueZ 获取 RSSI?

c - 为什么这个宏被定义为({ 1; })?

linux - 编译错误

linux - awk 删除行/记录并将其移动到第三个字段值为空的另一个文件

c++ - 了解#pragma omp parallel

c - 从循环中调用的函数中跳出循环

c - 为什么在 Linux 中使用 select

c - 为什么我在这个程序的 Console 中从来没有看到 Hello 文本?