Python 多线程中使用各自独立的变量

来源:互联网 发布:js移除绑定事件的方法 编辑:程序博客网 时间:2024/05/06 02:40

最简单的思路是每个 线程都使用各自私有的变量,但是python提供了一种更佳的解决方案

#!/usr/bin python# -*- coding:utf-8 -*-'''Created on 2015-6-20@author: huangpengthreading.local 线程中使用各自独立的局部变量'''import threadingimport random, timeclass 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.numberthreadLocal = 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

console:

<Thread(Thread-2, started 140011638880000)> [4, 0, 1, 8, 0, 6, 3, 1, 1, 3]<Thread(Thread-1, started 140011722458880)> [5, 5, 4, 0, 5, 7, 8, 6, 0, 7]<Thread(Thread-3, started 140011630487296)> [7, 6, 6, 8, 8, 3, 1, 2, 8, 4]<Thread(Thread-4, started 140011622094592)> [4, 0, 1, 2, 3, 1, 3, 2, 5, 1]<Thread(Thread-5, started 140011613701888)> [5, 6, 6, 9, 2, 4, 1, 9, 5, 7]


0 0