最简单的思路是每个 线程都使用各自私有的变量,但是python提供了一种更佳的解决方案
#!/usr/bin python
# -*- coding:utf-8 -*-
'''
Created on 2015-6-20
@author: huangpeng
threading.local 线程中使用各自独立的局部变量
'''
import threading
import random, time
class ThreadLocal():
def __init__(self):
self.local = threading.local()
def run(self):
time.sleep(random.random())
self.local.number =[]
for i in range (10):
self.local.number.append(random.choice(range(10)))
print threading.currentThread(), self.local.number
threadLocal = ThreadLocal()
threads = []
for i in range(5):
t = threading.Thread(target=threadLocal.run)
t.start()
threads.append(t)
for i in range(5):
threads[i].join
[4, 0, 1, 8, 0, 6, 3, 1, 1, 3]
[5, 5, 4, 0, 5, 7, 8, 6, 0, 7]
[7, 6, 6, 8, 8, 3, 1, 2, 8, 4]
[4, 0, 1, 2, 3, 1, 3, 2, 5, 1]
[5, 6, 6, 9, 2, 4, 1, 9, 5, 7]