Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Counting to 10

$
0
0
Hello!

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?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>