加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux,C:几秒后终止多线程(计时器?)

发布时间:2020-12-14 01:12:44 所属栏目:Linux 来源:网络整理
导读:Linux,C 我创建了多个线程来运行工作负载,我想在指定的秒/超时后发出停止/终止信号. 我如何用C实现这个? void *do_function(void *ptr){ //calculating,dothe workload here;}int run(struct calculate_node *node){ pthread_t threads[MAX_NUM_THREADS]; f
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,somefunc,NULL) != 0 )
    {
        perror( "create" );
        return 1;
    }

    sleep( 5 );
    setQuitFlag();
    pthread_join( threadID,NULL );
    fprintf( stderr,"end of mainn" );
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读