美文网首页
多线程:两个线程交互运行

多线程:两个线程交互运行

作者: 陈忠俊 | 来源:发表于2020-08-08 20:39 被阅读0次

    这里主要是建立了两个线程锁,运行自己线程调用函数时获得自己的锁,并释放另外一个线程调用函数的锁。

    以下运行,获得lock_num锁的时候,释放lock_char锁,反之一样。

    from threading import Thread, Lock, main_thread
    import time
    lock_num = Lock() 
    lock_char = Lock()
    
    # 线程类
    class MyThread(Thread):
        def __init__(self, thread_id, func, args):
            super().__init__()
            self.thread_id = thread_id
            self.func = func
            self.args = args
            self.count = len(args)
        def run(self):   
            while self.count:
                self.func(self.args)
                self.count -= 1
    
    # 函数一,打印出数字
    def print_num(nums):
        lock_num.acquire()
        if len(nums) > 0:
            print(nums.pop(0))
        lock_char.release()
        time.sleep(1)
    
    # 线程2,打印出字符
    def print_char(chars):
        lock_char.acquire()
        if len(chars) > 0:
            print(chars.pop(0))
        lock_num.release()
        time.sleep(1)
    
    nums = [1,2,3,4]
    chars = ['a', 'b', 'c', 'd']
    
    lock_num.acquire()
    t1 = MyThread('thread-1', print_num, nums) # 线程一
    t2 = MyThread('thread-2', print_char, chars) # 线程二
    
    t1.start() # 启动线程
    t2.start()
    t1.join() # 等待所有子线程结束
    t2.join()
    

    输出形式如下:

    a
    1
    b
    2
    c
    3
    d
    4
    

    另外一个方式,利用Condition。但是这里有个问题,在主线程退出之后,子线程不能自动退出。还没找到解决方法。

    from threading import Lock, Thread, Condition
    from queue import Queue
    import time
    
    cdt = Condition()
    
    class ThreadNum(Thread):
        def __init__(self, thread_id, args):
            super().__init__()
            self.thread_id = thread_id
            self.args = args
        
        def run(self):
            while True:
                if cdt.acquire():
                    if len(self.args) != 0:
                        print(self.args.pop(0))
                        cdt.notify()
                        cdt.wait()
                    else:
                        break
                    cdt.release()
                    time.sleep(0.3)
    
    class ThreadChar(Thread):
        def __init__(self, thread_id, args):
            super().__init__()
            self.thread_id = thread_id
            self.args = args
    
        def run(self):
            while True:
                if cdt.acquire():
                    if len(self.args) != 0:
                        print(self.args.pop(0))
                        cdt.notify()
                        cdt.wait()
                    else:
                        break
                    cdt.release()
                    time.sleep(0.3)
    
    th1 = ThreadNum('th1', [1,2,3,4,5,6,7,8])
    th2 = ThreadNum('th2', ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
    
    th1.start()
    th2.start()
    

    相关文章

      网友评论

          本文标题:多线程:两个线程交互运行

          本文链接:https://www.haomeiwen.com/subject/lhxkdktx.html