The output is not guaranteed as you expect it. I implemented a timestamp, which shows, when the put and get methods are called (time is relative to when init was called):[ 44491 ns] 0 --->[115427 ns] 1 --->[153189 ns] ---> 0[178376 ns] 2 --->[182891 ns] 3 --->[183518 ns] ---> 1[188542 ns] ---> 2[198661 ns] 4 --->[203461 ns] ---> 3[206636 ns] ---> 4[204180 ns] 5 --->[212146 ns] 6 --->[221019 ns] ---> 5[224146 ns] ---> 6[221877 ns] 7 --->[230976 ns] 8 --->[232130 ns] 9 --->[232347 ns] ---> 7[237920 ns] ---> 8[239051 ns] ---> 9[239312 ns] 10 --->[244770 ns] 11 --->[245918 ns] 12 --->[246106 ns] ---> 10...你应该知道,stdout 是两个线程共享的,那么锁是怎么实现的,谁知道呢.You should know, that stdout is shared by the two threads, so how the locking is implemented there, who knows.如果你想要同步输出,你必须把 printf 放入同步部分(在 put 和 get 方法中访问你的缓冲区之后).If you want synchronized output, you have to put printf into the synchronized sections (after accessing your buffer in the put and get methods).然后你得到输出:[ 31900 ns] 0 --->[ 77228 ns] ---> 0[ 85722 ns] 1 --->[ 90959 ns] ---> 1[ 95490 ns] 2 --->[ 99591 ns] ---> 2[103447 ns] 3 --->[107385 ns] ---> 3[111325 ns] 4 --->[115215 ns] ---> 4[119143 ns] 5 --->[123066 ns] ---> 5[126962 ns] 6 --->[130860 ns] ---> 6[134561 ns] 7 --->[138427 ns] ---> 7[142188 ns] 8 --->[146115 ns] ---> 8[149797 ns] 9 --->[153534 ns] ---> 9[157856 ns] 10 --->[161631 ns] ---> 10... 这篇关于多线程程序如何在 C 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 06:37