#include <stdio.h>
#include <pthread.h>
typedef struct {
int threadNum;
}thread_args;
void thread_func(void*vargp){
thread_args*id=(thread_args*)vargp;
printf("%i\n",id->threadNum);
}
int main() {
for(int i=0;i<20;i++) {
pthread_t id;
thread_args args;
args.threadNum=i;
pthread_create(&id,NULL,thread_func,(void*)&args);
}
pthread_exit(NULL);
return 0;
}
Adapted from https://www.geeksforgeeks.org/multithreading-c-2/.
So this is expected to output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
But shuffled in a random order to account for the concurrency of the threads.
The issue here is that it actually prints out this:
4
9
10
5
11
12
13
8
4
4
17
6
18
7
15
19
6
14
19
16
As you can see, there are duplicate numbers and 0-3 are just plain skipped.
I have done concurrency before in other frameworks before, and I have seen similar issues: what is happening here is that the i
is being passed as a reference (I think!) and so when the for
loop increments i
, it is incremented in all thread argument variables.
How can I avoid this?
NOTE: Everything is linking 100% properly and I'm on macOS.
PS: Sorry if this is a duplicate, I'm not very experienced with this.