2016-07-13 31 views
1

我想在两个独立的模块两个线程之间交换简单的数据,我找不到更好的方式做正确交换两个线程之间的DATAS在Python

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

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

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

我的第一个线程是一个GUI巫婆FLASK应用程序。在这个界面,我在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" 

的我不知道如何让这两个主题讨论。

回答

2

从你的描述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!') 
+0

我的问题是设置在烧瓶中的应用GUI事件对象,我不知道如何给事件到按钮功能 – kidz55

+0

您应该将事件传递给'ThreadGui',并在''button''函数中使用它。 – matino