先看一个例子:
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading # local_values = threading.local() class Foo(object): def __init__(self): self.name = 0 local_values = Foo() def func(num): local_values.name = num import time time.sleep(1) print(local_values.name,threading.current_thread().name) for i in range(5): th = threading.Thread(target=func, args=(i,), name='线程%s' % i) th.start()
4 线程0 4 线程1 4 线程3 4 线程2 4 线程4
上述结果不是我们想要的,local_values.name的值被最后一个覆盖了.............................
flask的request和session设置方式比较新颖,如果没有这种方式,那么就只能通过参数的传递。
flask是如何做的呢?
1. 本地线程,保证即使是多个线程,自己的值也是互相隔离。
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading local_values = threading.local() def func(num): local_values.name = num import time time.sleep(1) print(local_values.name, threading.current_thread().name) for i in range(20): th = threading.Thread(target=func, args=(i,), name='线程%s' % i) th.start()
from _thread import get_ident import threading def task(num): print(get_ident()) for i in range(10): th = threading.Thread(target=task,args=(i,),name='线程%s' % i) th.start()