Python简单线程同步

来源:互联网 发布:linux进程查看命令 top 编辑:程序博客网 时间:2024/05/19 18:42
__author__ = 'LL_YING''''多线程环境下,如果多个线程同时对某个数据进行修改,可能出现不可预料的结果。为保证数据被正确修改,就需要对多个线程进行同步。使用Thread对象的Lock和RLock实现简单的线程同步。如果某个数据在某一时刻只允许一个线程进行操作,则可以将操作放在acquire方法和release方法中间。'''import threadingimport timeclass mythread(threading.Thread):    def __init__(self, threadname):        threading.Thread.__init__(self, name=threadname)    def run(self):        global x        lock.acquire()        for i in range(3):            x = x + 1        time.sleep(2)        print(x)        lock.release()lock = threading.RLock()t1 = []for i in range(10):    t = mythread(str(i))    t1.append(t)x = 0for i in t1:    i.start()# 输出为:# 3# 6# 9# 12# 15# 18# 21# 24# 27# 30# 如果注释掉lock.acquire(),lock.release()和lock=threading.RLock(),输出为:# 30# 30# 30# 30# 30# 30# 30# 30# 30# 30
0 0
原创粉丝点击