gpt4 book ai didi

python - Python 中两个线程之间交换数据

转载 作者:行者123 更新时间:2023-12-01 03:50:17 26 4
gpt4 key购买 nike

我正在尝试在两个独立模块中的两个线程之间交换简单数据,但我找不到更好的方法来正确执行此操作

这是我的架构:我有一个启动两个线程的主脚本:

from core.sequencer import Sequencer
from gui.threadGui import ThreadGui

t1 = ThreadGui()
t2 = Sequencer()
t1.start()
t2.start()
t1.join()
t2.join()

我的第一个线程是一个带有 FLASK 应用程序的 GUI。在此 GUI 中,我按下 HTML 页面中的一个按钮,然后在按钮函数中将 ButtonState 切换为 True

from threading import Thread,RLock
from flask import Flask, render_template, request, url_for, redirect
GUI = Flask(__name__)

class ThreadGui(Thread):

def __init__(self):
Thread.__init__(self)

def run(self):
GUI.run()



wsgi_app = GUI.wsgi_app


@GUI.route('/')
def index():
print"INDEX"
return render_template("index.html")


@GUI.route('/prod')
def prod():
return render_template("prod.html")


@GUI.route('/maintenance')
def maintenance():
return render_template("maintenance.html")


@GUI.route('/button', methods = ['GET','POST'])
def button():
buttonState = True
print"le bouton est TRUE"
return redirect(url_for('prod'))

在我的第二个线程中,我需要收到更改通知

from threading import Thread,RLock
from globals import buttonState
import time


verrou = RLock()
class Sequencer(Thread):

def __init__(self):
Thread.__init__(self)

def run(self):
with verrou:
while 1:
if buttonState:
print"le bouton est true, redirection de l'ordre"
else:
time.sleep(2)
print"rien ne se passe"

我不知道如何让这两个线程进行讨论。

最佳答案

根据您的描述Event object看起来是最合理的解决方案:

class Sequencer(Thread):

def __init__(self, button_pressed_event):
Thread.__init__(self)
self._event = button_pressed_event

def run(self):
while not self._event.is_set():
time.sleep(2)
print ('Sleeping...')
print('Button was pressed!')

在 GUI 线程中,您只需在按下按钮后设置事件 (event.set())。

如果您不关心调试,您还可以简化您的 run 方法:

def run(self):
self._event.wait()
print('Button was pressed!')

关于python - Python 中两个线程之间交换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com