python多线程同步机制

力扣中刷到 “1114. 按序打印”,题目描述如下:

难度简单94收藏分享切换为英文关注

通过次数

14,189

提交次数

24,486

我们提供了一个类:

public class Foo {
  public void one() { print("one"); }
  public void two() { print("two"); }
  public void three() { print("three"); }
}
三个不同的线程将会共用一个 Foo 实例。

线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

 

示例 1:

输入: [1,2,3]
输出: "onetwothree"
解释: 
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。
示例 2:

输入: [1,3,2]
输出: "onetwothree"
解释: 
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。


由以上描述可知此题考查的是执行屏障的问题,可用线程同步的方式来解决,既然遇上这个题,就顺带复习一下多线程同步机制:Lock,Semaphores,Condition,Events,queue等概念。

queue:

queue模块在https://blog.csdn.net/tryhardsilently/article/details/102684750中已有总结,这里不多写。一下为本题用queue的实现:

import queue
class Foo:
    def __init__(self):
        self.tag1 = queue.Queue()
        self.tag2 = queue.Queue()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        # printFirst() outputs "first". Do not change or remove this line.
        printFirst()
        self.tag1.put(1)
        

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.tag1.get()
        # printSecond() outputs "second". Do not change or remove this line.
        printSecond()
        self.tag2.put(2)


    def third(self, printThird: 'Callable[[], None]') -> None:
        self.tag2.get()
        # printThird() outputs "third". Do not change or remove this line.
        printThird()

Lock:

构造方法:   Lock()
实例方法: 
    acquire([timeout]): 获取锁 ,使线程进入同步阻塞状态
    release(): 释放锁。线程释放前必须已获得锁,否则将抛出异常

Lock是可用的最低级的同步指令,Lock处于锁定状态时,不被特定的线程拥有。Lock包含两种状态——锁定和非锁定,以及两个基本的方法。锁定和释放的过程为:
     请求锁定 — 进入锁定池等待 — 获取锁 — 已锁定 — 释放锁

本题用Lock实现:

import threading
class Foo:
    def __init__(self):
        self.l1 = threading.Lock()
        self.l2 = threading.Lock()
        self.l1.acquire()
        self.l2.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        # printFirst() outputs "first". Do not change or remove this line.
        printFirst()
        self.l1.release()
        

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.l1.acquire()
        # printSecond() outputs "second". Do not change or remove this line.
        printSecond()
        self.l1.release()
        self.l2.release()


    def third(self, printThird: 'Callable[[], None]') -> None:
        self.l2.acquire()
        # printThird() outputs "third". Do not change or remove this line.
        printThird()
        self.l2.release()

Semaphores信号量

信号量是一个更高级的锁机制。信号量内部有一个计数器而不像锁对象内部有锁标识,而且只有当占用信号量的线程数超过信号量时线程才阻塞。这允许了多个线程可以同时访问相同的代码区。

Semaphore管理一个内置的计数器,每当调用acquire()时内置计数器-1;调用release() 时内置计数器+1;

计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。

Semaphores实现本题:

import threading
class Foo:
    def __init__(self):
        self.s1 = threading.Semaphore()
        self.s2 = threading.Semaphore()
        self.s1.acquire()
        self.s2.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        # printFirst() outputs "first". Do not change or remove this line.
        printFirst()
        self.s1.release()
        

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.s1.acquire()
        # printSecond() outputs "second". Do not change or remove this line.
        printSecond()
        self.s1.release()
        self.s2.release()


    def third(self, printThird: 'Callable[[], None]') -> None:
        self.s2.acquire()
        # printThird() outputs "third". Do not change or remove this line.
        printThird()
        self.s2.release()

Event

Event内部包含了一个标志位,初始的时候为false。
可以使用使用set()来将其设置为true;
或者使用clear()将其从新设置为false;
可以使用is_set()来检查标志位的状态;
另一个最重要的函数就是wait(timeout=None),用来阻塞当前线程,直到event的内部标志位被设置为true或者timeout超时。如果内部标志位为true则wait()函数理解返回。

Event实现本题:

import threading
class Foo:
    def __init__(self):
        self.e1 = threading.Event()
        self.e2 = threading.Event()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        # printFirst() outputs "first". Do not change or remove this line.
        printFirst()
        self.e1.set()
        

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.e1.wait()
        # printSecond() outputs "second". Do not change or remove this line.
        printSecond()
        self.e1.set()
        self.e2.set()


    def third(self, printThird: 'Callable[[], None]') -> None:
        self.e2.wait()
        # printThird() outputs "third". Do not change or remove this line.
        printThird()
        self.e2.set()

Condition
可以把Condition理解为一把高级的锁,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个锁对象(默认是RLock),可以在创建Condigtion对象的时候把锁对象作为参数传入。Condition也提供了acquire, release方法,其含义与锁的acquire, release方法一致,其实它只是简单的调用内部锁对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用锁(acquire)之后才能调用,否则将会报RuntimeError异常。):

Condition.wait([timeout]):  
wait方法释放内部所占用的锁,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有锁的时候,程序才会继续执行下去。

Condition.notify():
唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的锁。

Condition.notify_all() 
Condition.notifyAll()
唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的锁。

condition实现

import threading

class Foo:
    def __init__(self):
        self.c = threading.Condition()
        self.t = 0

    def first(self, printFirst: 'Callable[[], None]') -> None:
        self.res(0, printFirst)

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.res(1, printSecond)

    def third(self, printThird: 'Callable[[], None]') -> None:
        self.res(2, printThird)
        
    def res(self, val: int, func: 'Callable[[], None]') -> None:
        with self.c:
            self.c.wait_for(lambda: val == self.t) #参数是函数对象,返回值是bool类型
            func()
            self.t += 1
            self.c.notify_all()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值