2013-10-14 1 views
0

나는 실행중인 모듈에서 직접 변수를 변경하는 방법을 모색 해 왔습니다. 내가 원하는 것은 부하 테스트가 실행 중이고 수동으로 통화 속도를 조절할 수 있다는 것입니다.멀티 스레딩 (?) : 루프의 수동 간섭

방금 ​​만든 코드 (테스트되지 않은 e.d.) 아래에 아이디어가 있습니다.

class A(): 
    def __init__(self): 
     self.value = 1 
    def runForever(self): 
     while(1): 
      print self.value 
    def setValue(self, value): 
     self.value = value 

if __name__ == '__main__': 
    #Some code to create the A object and directly apply the value from an human's input 
    a = A() 

    #Some parallelism or something has to be applied. 
    a.runForever() 
    a.setValue(raw_input("New value: ")) 

편집 # 1 : 예, 지금 내가

답변

0

여기는 멀티 스레드 예제입니다. 이 코드는 파이썬 인터프리터에서는 작동하지만, IDLE의 Python 쉘에서는 작동하지 않습니다. 왜냐하면 raw_input 함수가 동일한 방식으로 처리되지 않기 때문입니다.

0

당신이 쓴 의사 코드는 스레딩/멀티가 작동하는 방식과 매우 유사 :-) a.setValue()을 공격하지 않을 것이라는 점을 알고있다 파이썬. "영원히"실행되는 스레드 (예를 들어)를 시작한 다음 내부 속도 값을 직접 수정하는 대신에 새 값을 제공하는 큐를 통해 메시지를 전송할 수도 있습니다.

체크 아웃 this question을 확인하십시오.

다음은 사용자가 요청한 것을 보여주는 데모입니다. 큐를 사용하여 스레드/프로세스에서 직접 호출하는 것을 선호합니다.

import Queue # !!warning. if you use multiprocessing, use multiprocessing.Queue 
import threading 
import time 


def main(): 
    q = Queue.Queue() 
    tester = Tester(q) 
    tester.start() 
    while True: 
     user_input = raw_input("New period in seconds or (q)uit: ") 
     if user_input.lower() == 'q': 
      break 
     try: 
      new_speed = float(user_input) 
     except ValueError: 
      new_speed = None # ignore junk 
     if new_speed is not None: 
      q.put(new_speed) 
    q.put(Tester.STOP_TOKEN) 

class Tester(threading.Thread): 
    STOP_TOKEN = '<<stop>>' 
    def __init__(self, q): 
     threading.Thread.__init__(self) 
     self.q = q 
     self.speed = 1 
    def run(self): 
     while True: 
      # get from the queue 
      try: 
       item = self.q.get(block=False) # don't hang 
      except Queue.Empty: 
       item = None # do nothing 
      if item: 
       # stop when requested 
       if item == self.STOP_TOKEN: 
        break # stop this thread loop 
       # otherwise check for a new speed 
       try: 
        self.speed = float(item) 
       except ValueError: 
        pass # whatever you like with unknown input 
      # do your thing 
      self.main_code() 
    def main_code(self): 
     time.sleep(self.speed) # or whatever you want to do 


if __name__ == '__main__': 
    main() 
+0

코드를 threadable 한 것으로 변환하는 방법을 알아봐야 할 것입니다. –