http://www.cs.colostate.edu/~cs370/Spring15/Workbook/thread_ex.txt
我的教授提供了上面的示例代码(不重复以保留他的IP),并且我对输出感到困惑。
有两个函数用作启动例程,T1和T2,并且有两个单独的for循环启动新线程。每个线程都有一个tid,应该在创建线程时匹配t的值,但是有几个相同函数的线程具有相同的tid,如他的示例输出结尾所示,即有两个T1线程与tid 1.为什么会发生这种情况?如果有4个T1线程,那么它是否应该生成0-3?
答案 0 :(得分:4)
您的教授设计错误,t
在主线程中更改其值,并且在不使用互斥的情况下由其他线程访问。
这里有clang
的TSan所说的话:
==================
WARNING: ThreadSanitizer: data race (pid=5810)
Read of size 4 at 0x7fff193c03e4 by thread T1:
#0 T1(void*) /home/brian/src/so/threading/ex.cpp:16 (exe+0x0000000a0497)
Previous write of size 4 at 0x7fff193c03e4 by main thread:
#0 main /home/brian/src/so/threading/ex.cpp:61 (exe+0x0000000a0881)
Location is stack of main thread.
Thread T1 (tid=5812, running) created by main thread at:
#0 pthread_create ??:0 (exe+0x000000045a8b)
#1 main /home/brian/src/so/threading/ex.cpp:62 (exe+0x0000000a085a)
SUMMARY: ThreadSanitizer: data race /home/brian/src/so/threading/ex.cpp:16 T1(void*)
==================
......接着......
T1 [0] count = 12
==================
WARNING: ThreadSanitizer: data race (pid=5810)
Write of size 1 at 0x7ff2f8aa2c80 by main thread:
#0 main /home/brian/src/so/threading/ex.cpp:70 (exe+0x0000000a0964)
Previous read of size 1 at 0x7ff2f8aa2c80 by thread T1:
#0 T1(void*) /home/brian/src/so/threading/ex.cpp:18 (exe+0x0000000a04de)
As if synchronized via sleep:
#0 sleep ??:0 (exe+0x00000003f7bd)
#1 main /home/brian/src/so/threading/ex.cpp:69 (exe+0x0000000a0952)
Thread T1 (tid=5812, running) created by main thread at:
#0 pthread_create ??:0 (exe+0x000000045a8b)
#1 main /home/brian/src/so/threading/ex.cpp:62 (exe+0x0000000a085a)
SUMMARY: ThreadSanitizer: data race /home/brian/src/so/threading/ex.cpp:70 main
==================
T1 thread 1 done.