繁体   English   中英

C,Pthreads-如何重新执行指定的函数或start_routine

[英]C , Pthreads - How to re-execute function or start_routine specified

我是C编程的新手,并且正在为此学习课程。 给我的任务如下

  1. 创建一个运算符(一个运算符作为一个线程)
  2. 首先创建10个零售商(每个线程一个)
  3. 最初创建10个客户(每个线程一个)

将来的任务需要之前创建的线程。 还有更多的任务,例如零售商通过运营商与客户沟通,但这不是我要问的

这是我的一些代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREAD 21


void* operator (void* arg) {
     //Logic here
}

void* retailer(void *arg) {
    //Logic here
}

void* customer(void* arg) {
   //Logic here
}

main() {
    pthread_t threads[NUM_THREAD];

    int i = 0;
    pthread_create(&threads[0],NULL , operator , NULL);
    printf("Operator created.\n");

    for ( i = 1 ; i < 11 ; i++) {
        pthread_create(&threads[i], NULL , retailers ,NULL);

    }

    for (i = 11 ; i < NUM_THREAD ; i++) {
        pthread_create(&threads[i], NULL , customers , NULL);

    }

}

预期输出为

Operator created.
Retailer 1 Created.
...
Retailer 10 Created.
Customer 1 Created.
...
Customer 10 Created.
..The rest of output are the action between Operator , retailers and customers which involves semaphores and other stuff

我已经在互联网上进行搜索,关于线程创建之后如何“重用”线程,我没有任何想法。 创建线程时,它应该开始执行pthread_create中指定的功能。 但是,该函数执行后,由于任务3之后的任务需要这些线程,它只是失去了任务1,2,3的含义。

要清楚,这是我的问题

  1. 如何创建线程并使之保持活动状态,以便以后可以重用该函数?
  2. 如果在线程的start_routine中添加else,是否是一种好方法?

为了回答您的第一个问题,线程功能通常由启动代码,一些描述的长时间运行循环和终止代码(例如以下伪代码)组成,如下所示:

def retailer:
    initialise thread-local stuff
    while termination condition not met:
        do some processing
    terminate thread-local stuff

因此,线程将继续运行,直到某个代码段(例如CTRL-C信号处理程序或用户告诉其停止的主线程)指示其应该停止为止。

请注意,上面的代码固有的是正确使用线程之间共享的保护资源(例如检查终止条件和“进行一些处理”中涉及的任何线程间通信),我没有明确提及,但是应该完成。

对于第二个问题,您几乎可以将所需的任何代码放入线程函数中,就像是普通的单线程代码一样。

线程引入了通常不需要关注的某些方面,例如竞争条件,线程本地存储或线程同步(互斥体,条件变量等),但是您可以使用普通的C控制流,例如if while不用担心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM