Python进阶(多线程)

多线程结构

import threading

def worker():#子线程要执行的具体逻辑代码函数
    print('threading')
    t1 = threading.current_thread()
    time.sleep(9)#通过休眠模拟子线程异步逻辑
    print(t1.getName())

new_t = threading.Thread(target=worker,name='dxc1')#构建子线程
new_t.start()#开启子线程

t = threading.current_thread()#构建主线程
print(t.getName())#主线程的代码执行不会受子线程的worker线程函数执行时间的影响

 

多线程隔离Local

import threading
from werkzeug.local import Local

my_obj = Local()#线程隔离对象
my_obj.b = 1

def worker():#新线程工作函数
    my_obj.b = 2
    print('in new thread b is:' + str(my_obj.b))#新线程中b是2

new_t = threading.Thread(target=worker,name='testThread')
new_t.start()
time.sleep(1)

#主线程
print('in main thread b is:' + str(my_obj.b))#主线程中b是1

 

多线程隔离LocalStack

import threading
from werkzeug.local import LocalStack

my_stack = LocalStack()#LocalStack保证两个线程会有两个栈,相互不干扰的线程隔离对象
my_stack.push(1)

#主线程
print('in main thread after push,value is:' + str(my_stack.top))#1

def worker():#新线程
    print('in new thread before push,value is:' + str(my_stack.top))#None
    my_stack.push(2)
    print('in new thread after push,value is:' + str(my_stack.top))#2

new_t = threading.Thread(target=worker,name='testThread')
new_t.start()
time.sleep(1)

#主线程
print('finally in main thread,value is' + str(my_stack.top))#1

 

posted @ 2019-07-07 08:17  周大侠小课堂  阅读(262)  评论(0编辑  收藏  举报