多线程打印输出问题

有可能。编译器很有可能生成这样的代码,不断重复:1: $1 = 2: $1 = $1 + 13: = $14: print $1AB两个thread,i存在addr位置。A1: $1 = // A.$1 = 0A2: $1 = $1 + 1 // A.$1 = 1A3: = $1 // = 1A4: print $1 // output 1A1: $1 = // A.$1 = 1B1: $1 = // B.$1 = 1A2: $1 = $1 + 1 // A.$1 = 2A3: = $1 // = 2A4: print $1 // output 2A1: $1 = // A.$1 = 2A2: $1 = $1 + 1 // A.$1 = 3A3: = $1 // = 3B2: $1 = $1 + 1 // B.$1 = 2B3: = $1 // = 2 // 这步把i从3写回2是关键。B4: print $1 // output 2A4: print $1 // output 3A1: $1 = // A.$1 = 2B1: $1 = // B.$1 = 2A2: $1 = $1 + 1 // A.$1 = 3A3: = $1 // = 3A4: print $1 // output 3B2: $1 = $1 + 1 // B.$1 = 3B3: = $1 // = 3B4: print $1 // output 3A1: $1 = // A.$1 = 3A2: $1 = $1 + 1 // A.$1 = 4A3: = $1 // = 4A4: print $1 // output 4...
■网友
Data race is undefined behavior,
■网友
补充一下,++i和print i两者生成的代码量和运行时间不在一个级别上,出现race condition很难,最终的结果很可能是数字顺序输出。 如果是这样的代码tmp = iprint tmpi = tmp + 1就更有可能出现题目中说的输出。
■网友
你是想强调3,3,3出现的这个情况吗?直觉告诉你两条线程只会一个数字只出现两次,但是多线程太奇妙了,如果你测出了这个情况请务必告知我。
■网友
显然不能这样 最好的办法就是push到一个线程 顺序打印


    推荐阅读