如何在完成线程后继续运行进程?

时间:2016-05-26 13:12:33

标签: c multithreading pthreads

当我试图打印所有线程的摘要(即一组线程的总计)时,我陷入困境。

下面的C代码运行10个线程,模拟销售门票的代理商。跑完后&完成线程(即在售完所有门票后),我想打印代理商列表和该代理商销售的相应票数。但是,主进程一旦到达行pthread_exit(NULL)(标有前面的注释)就终止,并且代码不返回main,它应该打印总计(此块)也标有评论。

有人能说出代码有什么问题吗?

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

struct ThreadArgs {
    int thNum;
    int *numTickets;
    int *soldTickets;
    sem_t *lock;
};

void *SellTickets(void *th) {
    struct ThreadArgs *thArgs;
    int sleepTime;

    thArgs = th;

    while (1) {
        sleepTime = rand();

        if (sleepTime % 2) {
            usleep(sleepTime % 1000000);
        }

        sem_wait(thArgs->lock);

        if (*thArgs->numTickets == 0) {
            break;
        }

        printf("There are %3d ticket(s). Agent %d sold a ticket.\n", *thArgs->numTickets, thArgs->thNum);
        (*thArgs->numTickets)--;
        sem_post(thArgs->lock);
        (*thArgs->soldTickets)++;
    }

    sem_post(thArgs->lock);
    pthread_exit(NULL);
}

void runThreads(int numAgents, int numTickets, int soldTickets[]) {
    struct ThreadArgs thArgs[numAgents];
    int agent;
    pthread_t th[numAgents];
    sem_t lock;

    sem_init(&lock, 1, 1);

    for (agent = 0; agent < numAgents; agent++) {
        thArgs[agent].thNum = agent;
        thArgs[agent].soldTickets = &soldTickets[agent];
        thArgs[agent].numTickets = &numTickets;
        thArgs[agent].lock = &lock;
        pthread_create(&th[agent], NULL, SellTickets, &thArgs[agent]);
    }
    // when debugging, the process terminates here
    pthread_exit(NULL);
}

int main() {
    int agent, numAgents, numTickets, soldTickets[10];

    numAgents = 10;
    numTickets = 150;

    for (agent = 0; agent < numAgents; agent++) {
        soldTickets[agent] = 0;
    }

    runThreads(numAgents, numTickets, soldTickets);

    // the process never executes the following block    
    for (agent = 0; agent < numAgents; agent++) {
        printf("Agent %d sold %d ticket(s).\n", agent, soldTickets[agent]);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

pthread_exit()退出一个帖子,甚至是“主要”线程。

如果main()结束,所有其他线程也会关闭。

由于“主要”线程预计会进行一些最终日志记录,因此它应该等到产生的所有线程都结束。

要在runThreads()中完成此操作,请将对

的调用替换为

      pthread_exit(NULL); 

通过为pthread_join()返回的所有PThread-ID调用pthread_create()的循环。

此外,您还要为所有pthread*()次调用添加错误检查,因为您应该为每个函数调用返回任何相关信息,例如指示 失败 电话。