2017-04-06 108 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