2016-07-13 37 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