简体   繁体   中英

C Why is the # of threads created in my code inconsistent?

The goal of my assignment is to create a loop to spawn 5 threads with integer arguments 0 through 4. I have 3 files: thread_demo.c that contains the main function, worker.c that contains the function to compute square of the argument, and header.h to keep the 2 files together.

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);
}

I have no compile errors, but the number of threads my code spawns is inconsistent. The pictures shown are my outputs from entering "5" 3 different times in which I have not made changes to the code. I'm not sure what causes this, I know I'm missing something but I don't know what it is. I also have to make "the main thread wait until all threads have completed", which is confusing to me. When I spawn the 5 threads, how do I know which is the main thread? I've never wrote code related to processes and threads so I'm completely lost. Any help would be greatly appreciated!

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

Your program is probably exiting before all your threads are complete. This would explain why you see different outputs on different runs: sometimes your program exits more or less quickly allowing less or more of the work to complete.

You need to keep your program from exiting (returning from main() ) until all your thread are finished. To do this, you can use pthread_join for each of the threads. Add after you create all the threads:

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

ptread_join will block (stop execution at that line) until the thread has terminated.

From the docs:

The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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