什么是线程不安全的Python代码的例子?

时间:2011-07-24 04:35:49

标签: python

在线程环境中运行不安全的Python代码有哪些示例?示例不必与框架相关 - 简单的Python示例和警告是首选。谢谢!

1 个答案:

答案 0 :(得分:3)

以下函数可能会以不可预知的方式写入文件/覆盖文件。

 import threading

 fp = open('f','w')

 def work1():
     for x in range(10000):
         fp.write('1')
 def work2():
     for x in range(10000):
         fp.write('2')

 t1 = threading.Thread(target = work1)
 t1.daemon = True
 t2 = threading.Thread(target = work2)
 t2.daemon = True

 t1.start()
 t2.start()
 t1.join()
 t2.join()

另一方面,这里的锁定机制会阻止文件输出混淆。

 import threading
 lock = threading.Lock()

 fp = open('f','w')

 def work1():
     with lock:
         for x in range(10000):
             fp.write('1')
 def work2():
     with lock:
         for x in range(10000):
             fp.write('2')

 t1 = threading.Thread(target = work1)
 t1.daemon = True
 t2 = threading.Thread(target = work2)
 t2.daemon = True

 t1.start()
 t2.start()
 t1.join()
 t2.join()