2017-04-06 73 views
0

感到很新的Python的用線不同類的變量acessing。所以我可能會問的可能不正確。什麼是想要做的是。從mainss創建一個線程並啓動線程。當線程開始我想它來訪問從創建線程,其中mainss類的變量和修改變量值。我想mainss執行休眠狀態,直到線程修改它的變量值之一。我怎樣才能做到這一點?這是我在下面嘗試的代碼。在mythread.py類的代碼註釋是我需要修改mainss類的計數變量的值修改和蟒蛇

main.py

#!/usr/bin/python 
import time 
from myThread import myThread 

class mainss(): 

    def __init__(self): 
     print "s" 

    def callThread(self): 
     global count 
     count = 1 
     # Create new threads 
     thread1 = myThread(1, "Thread-1", 1, count) 
     thread1.start() 
     # time.sleep(10) until count value is changed by thread to 3 
     print "Changed Count value%s " % count 
     print "Exiting" 

m = mainss() 
m.callThread() 

myThread.py提前

#!/usr/bin/python 

import threading 
import time 

exitFlag = 0 

class myThread (threading.Thread): 
    def __init__(self, threadID, name, counter, count): 
     threading.Thread.__init__(self) 
     self.threadID = threadID 
     self.name = name 
     self.counter = counter 
     self.count = count 
    def run(self): 
     print_time(self.name, 1, 5, self.count) 

def print_time(threadName, delay, counter, count): 
    from main import mainss 
    while counter: 
     if exitFlag: 
      threadName.exit() 
     time.sleep(delay) 
     count = count + 1 
     print "count %s" % (count) 

     # here i want to modify count of mainss class 

     counter -= 1 

謝謝

回答

0

我會用一個threading.EventQueue

這樣的事情,(請注意,我沒有這個測試自己,顯然你會不得不做出一些改變。 )

main.py

import Queue 
import threading 

from myThread import myThread 

class mainss: 

    def __init__(self): 
     self.queue = Queue.Queue() 
     self.event = threading.Event() 

    def callThread(self): 
     self.queue.put(1) # Put a value in the queue 

     t = myThread(self.queue, self.event) 
     t.start() 

     self.event.wait() # Wait for the value to update 

     count = self.queue.get() 

     print "Changed Count value %s" % count 

if __name__ == '__main__': 
    m = mainss() 
    m.callThread() 

myThread.py

import threading 

class myThread(threading.Thread): 

    def __init__(self, queue, event): 
     super(myThread, self).__init__() 
     self.queue = queue 
     self.event = event 

    def run(self): 
     while True: 
      count = self.queue.get() # Get the value (1) 

      count += 1 

      print "count %s" % (count) 

      self.queue.put(count) # Put updated value 

      self.event.set() # Notify main thread 

      break