且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

线程未按正确顺序打印

更新时间:2023-12-05 07:50:52

这是理解多线程的经典例子.线程并发运行,由操作系统调度程序调度.当我们谈论并行运行时,没有正确顺序"这样的东西.

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.

此外,还有为 stdout 输出刷新缓冲区之类的东西.意思是,当您打印"某些内容时,并不会保证它会立即发生,而是会在达到某个缓冲区限制/超时后发生.

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.

另外,如果你想以正确的顺序"完成工作,意味着等到第一个线程完成它的工作再开始下一个,考虑使用加入":http://man7.org/linux/man-pages/man3/pthread_join.3.html

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

更新:在这种情况下,将指针传递给 thread_id 也是不正确的,因为线程可能会打印不属于他的 id(感谢 Kevin)

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)