Python-线程-循环顺序打印abc

import threading

def showa():
    while True:
        lockc.acquire()  # 获取对方的锁,释放自己的锁
        print('a', end='')
        locka.release()



def showb():
    while True:
        locka.acquire()
        print('b', end='')
        lockb.release()
        # time.sleep(0.2)


def showc():
    while True:
        lockb.acquire()
        print('c', end='')
        # sys.stdout.flush()
        lockc.release()
        # time.sleep(0.2)


if __name__ == '__main__':
    locka = threading.Lock()  # 定义3个互斥锁
    lockb = threading.Lock()
    lockc = threading.Lock()

    t1 = threading.Thread(target=showa)  # 定义3个线程
    t2 = threading.Thread(target=showb)
    t3 = threading.Thread(target=showc)

    locka.acquire()  # 先锁住a,b锁,保证先打印a
    lockb.acquire()

    t1.start()
    t2.start()
    t3.start()

简单说明:

locka.acquire()
lockb.acquire()   

先是a和b锁着   故t2、t3线程无法拿到 a和b的锁所以无法执行打印 ; 此时c没有加锁, 故t1执行时可以获取到c锁,故先打印a(t1执行).

t1执行完之后是b和c锁着,a没有锁,故可以执行t2了

你可能感兴趣的:(Python)