I am trying to write a C program that makes use of pThreads. This particular program creates multiple threads (1 to maxNumber
) and does something with them (in the method threadMethod
). I pass a struct Arguments
to the pThread creator that contains necessary information about the threads, and threadNumber
is included in that struct. I am trying to make the program print which thread is doing work at that moment, but when I run the program, it always prints maxNumber
instead of threadNumber
. For example, if I want to make 3 threads, I should have an output like:
I am thread 1
I am thread 2
I am thread 3
But instead of the above, I get an output like:
I am thread 3
I am thread 3
I am thread 3
What is going wrong with my program? I have a feeling it has something to do with the struct, but I am not certain. Below is the relevant code.
Arguments *arg = malloc(sizeof(Arguments));
int i;
for (i = 0; i < maxNumber; i++) {
arg->threadNumber = (i + 1); /* eg. first thread is Thread 1, not Thread 0 */
if (pthread_create(&threads[i], NULL, threadMethod, (void *)arg)) {
printf("Error while creating thread\n");
return 1;
}
}
--------------------
void *threadMethod(void *arg) {
Arguments *argument;
int threadNumber;
argument = (Arguments*)arg;
threadNumber = argument->threadNumber;
printf("I am thread %d\n", threadNumber);
/* do stuff */
return NULL;
}
All your threads are sharing a single arg object, because you are only allocating it once. Move the malloc() inside the loop.
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.