動態

詳情 返回 返回

python 3個線程交替打印n、n的平方、n的立方 - 動態 詳情

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 頭像 flydean 頭像 zhangfeidezhu 頭像 jkkang 頭像 devlive 頭像 yelongyang 頭像 daixiaoyulq 頭像 binghe001 頭像 r0ad 頭像
點贊 9 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.