Stories

Detail Return Return

python 3個線程交替打印n、n的平方、n的立方 - Stories Detail

import threading


lock_a = threading.Lock()
lock_b = threading.Lock()
lock_c = threading.Lock()


def print_a():
    for i in range(2, 12, 2):
        lock_a.acquire()
        print(i)
        lock_b.release()


def print_b():
    for i in range(2, 12, 2):
        lock_b.acquire()
        print(i**2)
        lock_c.release()


def print_c():
    for i in range(2, 12, 2):
        lock_c.acquire()
        print(i**3)
        lock_a.release()


if __name__ == '__main__':
    lock_c.acquire()
    lock_b.acquire()

    t1 = threading.Thread(target=print_a)
    t2 = threading.Thread(target=print_b)
    t3 = threading.Thread(target=print_c)

    t1.start()
    t2.start()
    t3.start()
user avatar hankin_liu Avatar flydean Avatar zhangfeidezhu Avatar jkkang Avatar devlive Avatar yelongyang Avatar daixiaoyulq Avatar binghe001 Avatar r0ad Avatar
Favorites 9 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.