【廖雪峰老师python教程】——进程与线程

时间:2018-10-07 12:44:42   收藏:0   阅读:193

多进程


 

多线程


ThreadLocal


一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。

import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()

def process_student():
    # 获取当前线程关联的student:
    std = local_school.student
    print(Hello, %s (in %s) % (std, threading.current_thread().name))

def process_thread(name):
    # 绑定ThreadLocal的student:
    local_school.student = name
    process_student()

t1 = threading.Thread(target= process_thread, args=(Alice,), name=Thread-A)
t2 = threading.Thread(target= process_thread, args=(Bob,), name=Thread-B)
t1.start()
t2.start()
t1.join()
t2.join()

 

Hello, Alice (in Thread-A)
Hello, Bob (in Thread-B)

 

分布式进程


 




 

原文:https://www.cnblogs.com/ChaoyuanJam/p/9749718.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!