首页 > 解决方案 > 多次运行 pthread

问题描述

我希望一个线程运行无限次,以执行它接收到的 do_work() 函数中描述的任务。但是,该函数仅在 pthread_create() 子例程上调用。

我尝试在 while 循环中实现 sched_yield() 和 pthread_join() 例程。但它还没有奏效。

有没有可以再次调用现有线程的例程?

int main (int argc, char ** argv) {

    int period;
    int priority;
    int load;
    char schedule[15];
    
    period = atoi(argv[1]);
    priority = atoi(argv[2]);
    load = atoi(argv[3]);
    strncpy(schedule,argv[4],100);
    std::cout <<  " period : " << period <<"\n priority : "<< priority << "\n load : "<< load << "\n schedule : " << schedule <<std::endl;
    

    struct sched_param param;   
    pthread_t thread;
    int rc;
    sched_setscheduler (0, SCHED_FIFO , &param);

    
    std::cout << "main() : creating thread " << std::endl;
    rc = pthread_create(&thread, NULL, do_work, (void*)load);

    if (rc) {
         std::cout << "Error:unable to create thread " << rc << std::endl;
         exit(-1);
    }
    
    int i=0;
    
    struct sigaction action;
    struct itimerval timer;
    
    while(i<10000){
        pthread_join(thread, NULL);
        sched_yield();

        i++;
    }
    pthread_exit(NULL);
    
}

标签: c++multithreadingpthreadsposix

解决方案


您不调用线程,而是创建线程。通过这样做,您指定了一个将在新线程中调用的start_routine 。

如果要在循环中重复调用函数,则可以在start_routine中执行以下操作:

void* start_routine(void *arg) {
    while (active) { // active: atomic global boolean value
        do_work();
    }
    // if no longer active, 
    // there could be an option to wait to become active again,
    // or exit the thread
    pthread_exit(NULL);
}

pthread_join()仅在您想将线程与其他线程连接时才调用pthread_join()一直等到目标线程终止。通过加入线程,所有资源都归还给系统(清理)。


推荐阅读