多线程下对共享变量的写存在数据竞问题可导致数据与预期不一致。最近在研究race conditions漏洞,用以下python 代码记录一下,以此论证,如下:
from concurrent.futures import ThreadPoolExecutor
globalNum = 5
def test():
global globalNum
if globalNum >= 5:
print("globalNum >= 5 now")
globalNum -= 1
if __name__ == '__main__':
pool = ThreadPoolExecutor(max_workers=100)
for _ in range(100):
pool.submit(test)
以上代码运行时,预期输出一条“globalNum >= 5 now”,但实际情况可能输出2条及多条,如图: