2015-10-21 172 views
0

我有一個python腳本,它調用一個單獨的線程上的插件。插件必須執行一些命令並等待來自主腳本的信號,然後才能繼續。線程等待通信

我在插件中使用了wait(),並在調用腳本中設置並清除,但我猜測一旦插件線程被調用,主腳本將等待線程完成,然後再繼續。因此,設置和等待從未被調用,程序掛起。我附上了一個簡化版本的代碼。

#!/usr/bin/python 

import threading, os, sys, re, imp 

e = threading.Event() 

class PluginLoader(): 

# atexit.register(detective.terminate()) 
    ## getPlugins - Locate all plugins with plugin directory 
    # @param self   Class object pointer 
    # @param moduleName Name of module 

    def getPlugins(self, moduleName):   
     try: 
      # Folder in which the plugins are stored 
      self.pluginFolder = "/tmp/plugins" 

      # Give the value of the main module in json file. (This is the name omitting the .py extension) 
      self.mainModule = moduleName[0].strip(" ") 

      # Load plugin array 
      plugins = [] 
      possibleplugins = os.listdir(self.pluginFolder)   

      # Iterate over plugins to determine applicable plugin 
      for i in possibleplugins:    
       location=os.path.join(self.pluginFolder, i) 

       # Skip if not directory or plugin not in directory 
       if not os.path.isdir(location) or not self.mainModule + ".py" in os.listdir(location): 
        continue 

       # Otherwise, find the module 
       info = imp.find_module(self.mainModule, [location])   
       plugins.append({"name": i, "info": info})  

      return plugins    
     except OSError: 
      print "File or folder not found"    


    ## loadPlugin - Load plugin into script 
    # @param self  Class object pointer 
    # @param plugin Plugin object pointer 
    # @return Plugin object 

    def loadPlugin(self, plugin): 
     return imp.load_module(self.mainModule, *plugin["info"]) 


class Threads: 

    def run(self): 
     self.tuck() 
     raw_input("press entr")    
     e.set() 

    def tuck(self): 
     moduleName= ["hello"] 
     for i in pluginLoader.getPlugins(moduleName): 
      plugin = pluginLoader.loadPlugin(i)    
      threading.Thread(name = "block", target=plugin.run(e)).start() 
      e.set() 
      e.clear()  

pluginLoader=PluginLoader()  
t= Threads() 
t.run()    

以下腳本必須被複制到/ tmp目錄/ plugins目錄,並命名爲hello.py

#!/usr/bin/python 

from thre import * 

class wait: 
    flag = "" 
    def run(self,e): 
     self.flag = e 
     print "in main thread" 
     self.prints(e) 
     e.wait() 
     threading.Thread(target=self.prints12).start() 

    def prints(self,e): 
     for i in xrange(10): 
      print "world" 

    def prints12(self): 
     for i in xrange(10): 
      print "Hey" 


w = wait() 

def run (e)   : 
    w.run(e) 

回答

0

主要問題似乎是在這裏:

threading.Thread(name = "block", target=plugin.run(e)).start() 

plugin.run(e)將直接調用插件和塊的運行方法,從而使程序死鎖。這可能應該是:

threading.Thread(name = "block", target=plugin.run, args=(e,)).start()