Python利用Threading库实现2个程序多线程通信

本文介绍了一个基于Python的多线程应用案例,详细解释了如何使用锁来同步线程,确保线程安全地访问和修改全局变量。具体包括线程Thread-1负责获取模型推断结果并写入全局变量,而线程Thread-2则根据最新结果展示图片,同时清理过期数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

这里预设的需求是线程Thread-1-GetAttributes通过GetAttributesThread类获取模型的推断结果写入全局变量global_attribute中,假设推断时间1s,线程Thread-2-ShowImage根据最新推断结果展示推断图片3s,同时删除倒数第二张之前的推断结果。即总是用最新的结果进行展示,除非推断时间过长导致未有新的结果写入,则按保存的倒数第二张展示。若global_attribute栈空,则等待写入。
注意对全局变量global_attribute的操作时,要使用锁。
锁有两种状态——锁定和未锁定。每当一个线程比如Thread-2-ShowImage要访问共享数据global_attribute时,必须先获得锁定;如果已经有别的线程比如Thread-1-GetAttributes获得锁定了,那么就让线程Thread-2-ShowImage暂停,也就是同步阻塞;等到线程Thread-1-GetAttributes访问完毕,释放锁以后,再让线程Thread-2-ShowImage继续。
参考网址:线程同步

代码

#!/usr/bin/python3

import threading
import time
import random

global_attribute = []
class GetAttributesThread (threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
    def run(self):
        print ("当前线程: " + self.name)
        while True:
            global global_attribute
            attributes = compute_attributes()
            # 获取锁,用于线程同步
            threadLock.acquire()
            global_attribute.append(attributes)
            # 释放锁,开启下一个线程
            threadLock.release()
            print('ShowImageThread: global', global_attribute, '   ;attribute: ',attributes)

class ShowImageThread(threading.Thread):
    def __init__(self, threadId, name):
        threading.Thread.__init__(self)
        self.threadID = threadId
        self.name = name

    def run(self):
        print("当前线程: " + self.name)
        while True:
            global global_attribute
            if len(global_attribute) > 0:
                # 获取锁,用于线程同步
                threadLock.acquire()
                newest_att = global_attribute.pop()
                if len(global_attribute) > 1:
                    global_attribute = [global_attribute[-1]]
                # 释放锁,开启下一个线程
                threadLock.release()
                print("当前线程: " ,self.name, "  ;展示图片3s: ", newest_att)
                time.sleep(3)
            else:
                time.sleep(0.5)




def compute_attributes():
    '''
    模拟模型推断得到attributes的过程
    :return:
    '''
    a = random.random()
    b = int(100*a)
    time.sleep(1)
    return b

threadLock = threading.Lock()
threads = []

# 创建新线程
thread1 = GetAttributesThread(1, "Thread-1-GetAttributes")
thread2 = ShowImageThread(2, "Thread-2-ShowImage")

# 开启新线程
thread1.start()
thread2.start()

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值