Thread not printing out in correct order

前端 未结 1 588
暗喜
暗喜 2021-01-21 07:07

I\'m fairly new to threads in C. For this program I need to declare a thread which I pass in a for loop thats meant to print out the printfs from the thread.

I can\'t se

相关标签:
1条回答
  • 2021-01-21 07:49

    That's the classic example of understanding multi-threading. The threads are running concurrently, scheduled by OS scheduler. There is no such thing as "correct order" when we are talking about running in parallel.

    Also, there is such thing as buffers flushing for stdout output. Means, when you "printf" something, it is not promised it will happen immediately, but after reaching some buffer limit/timeout.

    Also, if you want to do the work in the "correct order", means wait until the first thread finishes it's work before staring next one, consider using "join": http://man7.org/linux/man-pages/man3/pthread_join.3.html

    UPD: passing pointer to thread_id is also incorrect in this case, as a thread may print id that doesn't belong to him (thanks Kevin)

    0 讨论(0)
提交回复
热议问题