zoukankan      html  css  js  c++  java
  • 交替打印

    有两个数组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()
  • 相关阅读:
    如何替换文件中的部分内容?
    将文件中的行倒序输出,并写入文件
    如何统计文件中除去空行的数据的行数?
    统计文件行数,统计特殊行(例如,统计含有数字的行数)
    Array,String,Set,Map
    python 操作 word 图片 消失
    es6
    Promise
    英文
    前端框架vue.js系列(9):Vue.extend、Vue.component与new Vue
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13606482.html
Copyright © 2011-2022 走看看