交替打印

有两个数组a和b, 有两个线程分别读取数组a和数组b,线程1循环打印数组a中的数字,线程2循环打印数组b中的数,要求交叉,要求第一个数组先输出。

import threading
#method1:协程
def sol(strs):
    for s in strs:
        res = yield s
        print(res)
        print(s)
it = sol(['a', 'b', 'c', 'd'])
next(it)
for num in [1, 2, 3, 4]:
    try:
        it.send(num)
    except StopIteration as e:
        pass
#用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,
# 必须捕获StopIteration错误,返回值包含在StopIteration的value中

#method2:信号量
def printNumber(nums):
    for num in nums:
            s1.acquire()
            print(num)
            s2.release()


def printAlpha(strs):
    for s in strs:
        s2.acquire()
        print(s)
        s1.release()

if __name__ == "__main__":
    s1 = threading.Semaphore(1)
    s2 = threading.Semaphore(0)
    threads = []
    threads.append(threading.Thread(target=printNumber, args=([5, 6, 7, 8], )))
    threads.append(threading.Thread(target=printAlpha, args=(['e', 'f', 'g', 'h'], )))
    for thr in threads:
        thr.start()
    for thr in threads:
        thr.join()

#method3:条件变量
def printNum2(nums):
    for num in nums:
        with con:
            global count
            if count % 2 != 0:
                con.wait()
            count += 1
            print(num)
            con.notify()

def printAlpha2(strs):
    for s in strs:
        with con:
            global count
            if count % 2 != 1:
                con.wait()
            count += 1
            print(s)
            con.notify()

if __name__ == "__main__":
    global count
    count = 0
    con = threading.Condition()
    threads = []
    threads.append(threading.Thread(target=printNum2, args=([9, 10, 11, 12], )))
    threads.append(threading.Thread(target=printAlpha2, args=(['i', 'j', 'k', 'l'], )))
    for t in threads:
        t.start()
    for tt in threads:
        tt.join()

 

posted @ 2020-09-03 11:06  LinBupt  阅读(240)  评论(0编辑  收藏  举报