Hello!
Why isn't this program counting from 1 to 10?
Writeloop is supposed to count from 1 to 10. But somehow, the pthread_command is doing something from stopping that happen. I get numbers in a random order. I'm not that familiar with C, and from what I understand, it seems like that I've created 10 threads. They have no order, so all of them are racing or something.
How could I fix this?
Why isn't this program counting from 1 to 10?
01 int g_ant = 0; /* global declaration */
02
03 void *writeloop(void *arg) {
04 while (g_ant < 10) {
05 g_ant++;
06 usleep(rand()%10);
07 printf("%d\n", g_ant);
08 }
09 exit(0);
10 }
11
12 int main(void)
13 {
14 pthread_t time;
15 pthread_create(&time, NULL, writeloop, NULL);
16 writeloop(NULL);
17 pthread_join(time, NULL);
18 return 0;
19 }
Writeloop is supposed to count from 1 to 10. But somehow, the pthread_command is doing something from stopping that happen. I get numbers in a random order. I'm not that familiar with C, and from what I understand, it seems like that I've created 10 threads. They have no order, so all of them are racing or something.
How could I fix this?