[英]stdout order with multiple threads
假設我有這樣的代碼:
main() {
start thread;
put data in task queue;
do some stuff
wait for data in result queue;
printf ("main got result\n");
fflush(stdout);
}
thread() {
while (!done) {
wait for data in task queue;
printf ("thread finished processing\n");
fflush(stdout);
put data in result queue;
}
}
如果我的線程安全數據隊列正常工作,是否可以獲取如下所示的輸出?
main got result
thread finished processing
stdio可以像這樣重新排序嗎,還是可以肯定的證明我的“線程安全”隊列不是?
如果我使用C ++進行編譯並在上面的代碼的main的“做一些事情”部分中使用iostreams(但仍在顯示的地方使用printf),答案是否會更改?
不。
即使您異步運行兩個線程(我也不知道您是否在這里),每個線程中的命令也會按順序執行。
因此,您的thread()將首先打印“ tread完成的處理”,然后將數據放入結果隊列。 只有這樣,您的main()才會收到消息並打印“主要結果”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.