threading.local

import threading
import time


def music(a,b):
   fo = open("test.txt1", "w")
    fo.write(a+b)
    fo.close()

def move(c,d):
   fo = open("test.txt2", "w")
    fo.write(c+d)
    fo.close()

# 关闭文件
fo.close()

threads = []
t1 = threading.Thread(target=music,args=("aa","bb"),name="aaaaaa")
threads.append(t1)
t2 = threading.Thread(target=move,args=("cc","dd"),name="bbbbbb")
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(False)
        t.start()

    print "all over"

 

Python提供了 threading.local 类,将这个类实例化得到一个全局对象,

但是不同的线程使用这个对象存储的数据其它线程不可见(本质上就是不同的线程使用这个对象时为其创建一个独立的字典)。

参考链接

https://www.cnblogs.com/i-honey/p/8051668.html

https://www.liaoxuefeng.com/wiki/1016959663602400/1017630786314240

import threading

workinfo = threading.local()

def work(num):
    workinfo.num = num
    print workinfo.num

for i in range(10):
        t1 = threading.Thread(target=work,args=(i,))
        t1.start()

 

posted on 2021-01-02 20:37  思此狂  阅读(87)  评论(0编辑  收藏  举报

导航