C为什么在我的代码中创建的线程数不一致?

时间:2019-03-07 22:56:36

标签: c multithreading

我的任务目标是创建一个循环,以生成5个具有0到4整数参数的线程。我有3个文件:thread_demo.c包含主要功能,worker.c包含用于计算平方的函数。参数和header.h来将2个文件放在一起。

thread_demo.c

#include "header.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

#define NUM_THREADS 5
#define PROMPT_SIZE 5

int main(){
        pthread_t threads[NUM_THREADS];
        pthread_attr_t pthread_attributes;

        int *prompt;
        scanf("%d", &prompt);

        for(int i = 0; i < NUM_THREADS; i++){
                pthread_create(&threads[i], &pthread_attributes, &worker, (void *) prompt);
        } 
} 

worker.c

#include "header.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void *worker(void * num){
        int *input;
        input = (int*) &num;

        // Calculate square
        int output = *input * *input;

        printf("The square of %d", *input);
        printf(" is %d.\n", output);

        pthread_exit(NULL);
}

我没有编译错误,但是我的代码产生的线程数不一致。显示的图片是我在3次不同的时间输入“ 5”后未更改代码的输出。我不确定是什么原因造成的,我知道我遗漏了一些东西,但我不知道它是什么。 我还必须使“主线程等待所有线程完成”,这使我感到困惑。当我生成5个线程时,我怎么知道哪个是主线程? 我从未写过与进程和线程相关的代码,所以我完全迷路了。任何帮助将不胜感激!

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

您的程序可能在所有线程完成之前退出。这可以解释为什么您在不同的运行中看到不同的输出:有时您的程序或多或少地退出,以允许更少或更多的工作完成。

您需要防止程序退出(从main()返回),直到所有线程结束。为此,您可以为每个线程使用pthread_join。创建所有线程后添加:

for(int i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i]);
}

ptread_join将阻塞(在该行停止执行),直到线程终止。

从文档中

  

pthread_join()函数等待线程指定的线程          终止。如果该线程已经终止,则          pthread_join()立即返回。线程指定的线程          必须可以加入。

     

http://man7.org/linux/man-pages/man3/pthread_join.3.html