python笔记10-多线程之线程同步(锁lock)

前言

关于吃火锅的场景,小伙伴并不陌生,吃火锅的时候a同学往锅里下鱼丸,b同学同时去吃掉鱼丸,有可能会导致吃到生的鱼丸。
为了避免这种情况,在下鱼丸的过程中,先锁定操作,让吃火锅的小伙伴停一会,等鱼丸熟了再开吃,那么python如何模拟这种场景呢?

未锁定

1.如果多个线程同时操作某个数据,会出现不可预料的结果。比如以下场景:当小伙伴a在往火锅里面添加鱼丸的时候,小伙伴b在同时吃掉鱼丸,这很有可能导致刚下锅的鱼丸被夹出来了(没有熟),或者还没下锅,就去夹鱼丸(夹不到)。

# coding=utf-8
import threading
import time

def chiHuoGuo(people, do):
    print("%s 吃火锅的小伙伴:%s" % (time.ctime(),people))
    time.sleep(1)
    for i in range(3):
        time.sleep(1)
        print("%s %s正在 %s 鱼丸"% (time.ctime(), people, do))
    print("%s 吃火锅的小伙伴:%s" % (time.ctime(),people))


class myThread (threading.Thread):   # 继承父类threading.Thread
    def __init__(self, people, name, do):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people
        self.do = do

    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)

        chiHuoGuo(self.people, self.do)     # 执行任务
        print("qq交流群:226296743")
        print("结束线程: " + self.name)

print("yoyo请小伙伴开始吃火锅:!!!")

# 设置线程组
threads = []

# 创建新线程
thread1 = myThread("xiaoming", "Thread-1", "添加")
thread2 = myThread("xiaowang", "Thread-2", "吃掉")

# 添加到线程组
threads.append(thread1)
threads.append(thread2)

# 开启线程
for thread in threads:
    thread.start()

# 阻塞主线程,等子线程结束
for thread in threads:
    thread.join()

time.sleep(0.1)
print("退出主线程:吃火锅结束,结账走人")

运行结果:

线程同步(锁lock)

1.为了避免以上这种情况发生,就引入锁的概念,锁有两种状态:锁定和未锁定

2.每当一个线程a要访问共享数据时,必须先获得锁定;如果已经有别的线程b获得锁定了,那么就让线程a暂停,也就是同步阻塞;等到线程b访问完毕,释放锁以后,再让线程a继续。

3.用threading.Lock()这个类里面的两个方法

  • acquire() 锁住
  • release() 释放锁
# coding=utf-8
import threading
import time

def chiHuoGuo(people, do):
    print("%s 吃火锅的小伙伴:%s" % (time.ctime(),people))
    time.sleep(1)
    for i in range(3):
        time.sleep(1)
        print("%s %s正在 %s 鱼丸"% (time.ctime(), people, do))
    print("%s 吃火锅的小伙伴:%s" % (time.ctime(),people))


class myThread (threading.Thread):   # 继承父类threading.Thread

    lock = threading.Lock()  # 线程锁

    def __init__(self, people, name, do):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people
        self.do = do

    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)

        # 执行任务之前锁定线程
        self.lock.acquire()

        chiHuoGuo(self.people, self.do)     # 执行任务

        # 执行完之后,释放锁
        self.lock.release()

        print("qq交流群:226296743")
        print("结束线程: " + self.name)

print("yoyo请小伙伴开始吃火锅:!!!")

# 设置线程组
threads = []

# 创建新线程
thread1 = myThread("xiaoming", "Thread-1", "添加")
thread2 = myThread("xiaowang", "Thread-2", "吃掉")

# 添加到线程组
threads.append(thread1)
threads.append(thread2)

# 开启线程
for thread in threads:
    thread.start()

# 阻塞主线程,等子线程结束
for thread in threads:
    thread.join()

time.sleep(0.1)
print("退出主线程:吃火锅结束,结账走人")

运行结果:

python自动化交流 QQ群:779429633

posted @ 2018-01-22 15:36  上海-悠悠  阅读(1978)  评论(0编辑  收藏  举报