Python之多线程编程2,线程间的通信(全局变量与Queue)

Python之多线程编程2,线程间的通信

1、通过全局变量线程间通信

  • 创建全局变量
value=[]
  • 创建函数调用全局变量
#向列表队尾追加元素
def function_append(n, threadname):
    global value
    print(f"运行线程为:{threadname},value的值为{value}")
    for i in range(n):
        value.append(i)
        print(f"添加后value的值为{value}")
        
#向列表队尾删除元素
def function_pop(n,threadname):
    global value
    print(f"运行线程为:{threadname},value的值为{value}")
    for i in range(n):
        value.pop()
    print(f"删除最后一个元素后value的值为{value}")
  • 主函数实现
if __name__=="__main__":
    print(f"value的初始值为{value}")
    thread1 = threading.Thread(target=function_append, args=[5, "thread1"])
    thread2 = threading.Thread(target=function_pop, args=[5,"thread2"])
    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()
    print(f"最终value的值为{value}")

运行结果:

在这里插入图片描述

2、通过Queue库实现线程通信

  • 导入queue库
from queue import Queue
  • 在主函数定义 queue对象
maxsize属性为queue队列的最大线程值
myqueue = Queue(maxsize=100)
  • 两个线程函数的编写
def function_put(queue, threadname):
    print(f"运行线程为:{threadname}")
    for i in range(3):
        time.sleep(3)
        queue.put(f"这是一个网址/{i}")
    print(f"结束线程{threadname}\n")
    # print(f"添加后value的值为{queue.get()}\n")


def function_get(queue, threadname):
    while True:
        print(f"运行线程为:{threadname}")
        print(f"获取queue的值为{queue.get()}")
  • 主函数编写
if __name__ == "__main__":
    myqueue = Queue(maxsize=100)

    thread1 = threading.Thread(target=function_put, args=[myqueue, "thread1"])
    thread2 = threading.Thread(target=function_get, args=[myqueue, "thread2"])
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

运行结果:

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值