简体   繁体   English

在Python中的两个线程之间交换数据

[英]Exchanging datas between two threads in Python

I'm trying to exchange simple data between two threads in two separated modules and I can't find the better way to do it properly 我正在尝试在两个单独的模块中的两个线程之间交换简单数据,但我找不到更好的方法来正确地执行此操作

here is my architecture : I have a main script which launch my two threads : 这是我的体系结构:我有一个启动两个线程的主脚本:

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

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

My first thread is a GUI witch a FLASK application. 我的第一个线程是FLASK应用程序的GUI女巫。 In this GUI, I press a button in my HTML page and I switch my buttonState to True in the button function 在此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'))

in my second thread, I need to be notified of the change 在第二个线程中,需要将更改通知我

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"

I don't know the way to make those two threads discuss. 我不知道如何讨论这两个主题。

From your description Event object looks like the most reasonable solution: 根据您的描述, 事件对象看起来是最合理的解决方案:

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!')

In your GUI thread you simply need to set the event ( event.set() ) once the button is pressed. 在您的GUI线程中,只需按一下按钮即可设置事件( event.set() )。

You could also simplify your run method if you don't care about debugging: 如果您不关心调试,也可以简化run方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM