0

Here is the code that I tried to create threads.

#include <stdio.h>
#include <pthread.h>
#define THREAD_NO 10

void *mythread(void *arg) {
    int *id = (int *)arg;
    printf("my id is %d\n", *id);
}

int main(){
    pthread_t p[THREAD_NO];
    int i = 0;
    for(i=0; i<THREAD_NO; i++){
        pthread_create(&p[i], NULL, mythread, &i);
    }

    for(i=0; i<THREAD_NO; i++){
    pthread_join(p[i], NULL);
    }
    return 0;
}

When I run this code to create threads, there are always duplicate ids in the output. Where is the problem and how can I solve it? Thanks a lot!

  • 2
    You're passing `i` by reference so you have a race condition when you subsequently perform `int *id = (int *)arg;`. – G.M. Oct 27 '22 at 18:49
  • 1
    You're not returning anything from a function supposed to return a pointer. I'm not sure if there's a special exception like for `main()`, but that could cause "undefined behaviour". In any case, all threads receive a pointer to the same object as parameter, so it's not a surprise that they see duplicate values when dereferencing the pointer. – Ulrich Eckhardt Oct 27 '22 at 18:53

0 Answers0