如何创建和使用在线程内部用的全局对象
'''
threading.local()
local类用于创建一个全局对象,不过改该对象只能在线程内部使用,也就是说吗,全局是针对一个线程而言的
'''
import threading
import time
a = threading.local()
def worker():
a.x = 0
for i in range(20):
time.sleep(0.01)
a.x += 1
print(threading.current_thread(), a.x)
if __name__ == '__main__':
for i in range(10):
threading.Thread(target=worker).start()
<Thread(Thread-6, started 24600)> 20
<Thread(Thread-12, started 12432)> 20
<Thread(Thread-10, started 23456)> 20
<Thread(Thread-11, started 16156)> 20
<Thread(Thread-9, started 22104)><Thread(Thread-13, started 11292)> 20<Thread(Thread-7, started 3968)> 20
<Thread(Thread-14, started 15756)> 20
<Thread(Thread-8, started 11416)> 20
<Thread(Thread-15, started 10864)> 20
20
正文完