import threading import time from werkzeug.local import Local, LocalStack my_local = Local() my_local.a = 'a' my_stack = LocalStack() my_stack.push(1) print(my_stack.top) def worker(): print('I am a thread worker') print(my_stack.top) t = threading.current_thread() # time.sleep(10) print(t.getName()) my_local.a = 'b' print(my_local.a) my_stack.push(2) print(my_stack.top) new_t1 = threading.Thread(target=worker, name='new thread1') new_t1.start() # new_t2 = threading.Thread(target=worker, name='new thread2') # new_t2.start() time.sleep(1) t = threading.current_thread()
因为在flask中都是用同一个变量名去引用相似的一类对象,如request引用Request对象,如何正确区分? flask通过包装成上下文对象,通过栈的特性,来保证上下文对象的存储和一致性(AppContext对象和RequestContext对象配套)。 线程隔离特性,保证线程之间操作各自的栈而互不干扰。(Request对象因为实例化了多个,所以需要隔离,而核心对象实际上只有一个,隔不隔离没有意义。) 意义在于:能使当前的线程能够正确引用到他自己所创建的对象,而不是引用到其他线程所创建的对象。虽然都叫相同的名字,但是从各自的栈顶取。从而保证不同请求的隔离性。 为什么要用一个栈来存取上下文对象? 实际上多线程模式下,一个请求由一个线程来处理,请求来进栈,处理完出栈,不需要保存多个上下文。但有些情况下,如离线脚本或单元测试时,可能会需要推入多个上下文,故需要一个容器来存取。 ''' import time from threading import Thread, current_thread from werkzeug.local import Local, LocalStack obj = Local() obj.a = 1 print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a) def manipulate(): obj.a = 2 print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a) newThread = Thread(name='newThread', target=manipulate) newThread.start() time.sleep(1) print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a) # 线程隔离栈的试验
# -*- coding: utf-8 -*- # @Time : 2019/4/10 19:59 # @Author : Lwq # @File : testthread2.py # @Software: PyCharm import threading import time from werkzeug.local import Local ''' 线程有隔离 ''' test = Local() test.a = 1 def work(): test.a = 2 print('new thread' + str(test.a)) thread_1 = threading.Thread(target=work) thread_1.start() # 停留一秒是确保线程1执行完成 time.sleep(1) print('main thread' + str(test.a))
import threading import time from werkzeug.local import Local class A: a = 10 def __str__(self): return "A: <{}>".format(self.a) # 主线程 my_obj = Local() my_obj.a = 10 def worker(): my_obj.a = 20 print('in the new thread t1 is : {}'.format(my_obj.a)) print("in the workder, get_indent(): {}".format(threading.get_ident())) t1 = threading.Thread(target=worker, name='t1_thread') t1.start() t1.join()
import threading import time from werkzeug.local import Local my_obj = Local() my_obj.a = 1 def worker(): my_obj.a = 2 print("new thread a is ", my_obj.a) new_thread = threading.Thread(target=worker, name="new_thread") new_thread.start() time.sleep(2) print("main thread a is", my_obj.a)