2013-07-17 6 views
1

나는이 스크립트를 가지고 있으며, kill을 파이프를 통해 리스너에게 보낼 때 프로세스를 죽이기 위해 리스너 스레드를 생성하는 2 개의 개별 프로세스가 있습니다.이 스크립트를 간소화하는 방법

from multiprocessing import Process, Pipe 
    from threading import Thread 
    import time 

    subAlive = True 
    testAlive = True 

    def sub_listener(conn): #listens for kill from main 
     global subAlive 
     while True: 
      data = conn.recv() 
      if data == "kill": 
      subAlive = False #value for kill 
      break 

    def test_listener(conn): #listens for kill from main 
     global testAlive 
     while True: 
       data = conn.recv() 
       if data == "kill": 
       testAlive = False #value for kill 
       break 

    def subprocess(conn, threadNum): 
     t = Thread(target=sub_listener, args=(conn,)) 
     count = 0 
     threadVal = threadNum 
     t.start() 
     while subAlive: 
       print "Thread %d Run number = %d" % (threadVal, count) 
       count = count + 1 


    def testprocess(conn, threadNum): 
     t = Thread(target=test_listener, args=(conn,)) 
     count = 0 
     threadVal = threadNum 
     t.start() 
     while testAlive: 
       print "This is a different thread %d Run = %d" % (threadVal, count) 
       count = count + 1 


    sub_parent, sub_child = Pipe() 
    test_parent, test_child = Pipe() 
    runNum = int(raw_input("Enter a number: ")) 
    threadNum = int(raw_input("Enter number of threads: ")) 

    print "Starting threads" 

    for i in range(threadNum): 
     p = Process(target=subprocess, args=(sub_child, i)) 
     p.start() 

    print "Subprocess started" 

    for i in range(threadNum): 
     p2 = Process(target=testprocess, args=(test_child, i)) 
     p2.start() 

    print "Testproccess started" 

    print "Starting run" 

    time.sleep(runNum) 

    print "Terminating Subprocess run" 
    for i in range(threadNum): 
     sub_parent.send("kill") #sends kill to listener 

    print "Terminating Testprocess run" 
    for i in range(threadNum): 
     test_parent.send("kill") #sends kill to listener 

    p.join() 
    p2.join() 

Id는 내가 호출하는 모든 프로세스에 대해 하드 코딩 된 별도의 수신기 기능을 필요로하지 않습니다. 스레드가 스폰 될 때 전역 변수 전달에 대해 생각하고있었습니다. 전역 변수는 실제로는 리스너 함수 간의 유일한 차이점입니다. 고마워요!

+1

들여 쓰기를 수정 해 주시겠습니까? 고마워요 :) – woozyking

+0

죄송합니다 한판 승부 그 –

+0

이제 괜찮아 보이네 :) 고마워. – woozyking

답변

2

globals() 사전을 통해 전역에 액세스 할 수 있습니다.

>>> foo = 'value' 
>>> def change(name): 
... globals()[name] = 'changed' 
... 
>>> change('foo') 
>>> foo 
'changed' 

하지만 난 제안 :

alive = {} 
def sub_listener(conn, key): #listens for kill from main 
    while True: 
     data = conn.recv() 
     if data == "kill": 
     alive[key] = False #value for kill 
     break 

를 예를 들면,

from multiprocessing import Process, Pipe 
from threading import Thread 
import time 

alive = { 
    'sub': 1, 
    'test': 1, 
} 

def listener_factory(key): 
    def listener(conn): #listens for kill from main 
     while True: 
      data = conn.recv() 
      if data == "kill": 
       alive[key] = False #value for kill 
       break 
    return listener 

def process_factory(key): 
    listener = listener_factory(key) 
    def subprocess(conn, threadNum): 
     t = Thread(target=listener, args=(conn,)) 
     count = 0 
     threadVal = threadNum 
     t.start() 
     while alive[key]: 
      print "Thread[%s] %d Run number = %d" % (key, threadVal, count) 
      count = count + 1 
    return subprocess 

def main(): 
    sub_parent, sub_child = Pipe() 
    test_parent, test_child = Pipe() 
    runNum = int(raw_input("Enter a number: ")) 
    threadNum = int(raw_input("Enter number of threads: ")) 
    print "Starting threads" 
    for i in range(threadNum): 
     p = Process(target=process_factory('sub'), args=(sub_child, i)) 
     p.start() 
    print "Subprocess started" 
    for i in range(threadNum): 
     p2 = Process(target=process_factory('test'), args=(test_child, i)) 
     p2.start() 
    print "Testproccess started" 
    print "Starting run" 
    time.sleep(runNum) 
    print "Terminating Subprocess run" 
    for i in range(threadNum): 
     sub_parent.send("kill") #sends kill to listener 
    print "Terminating Testprocess run" 
    for i in range(threadNum): 
     test_parent.send("kill") #sends kill to listener 
    p.join() 
    p2.join() 

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

내가 갖고있는 것과는 다른 점은 무엇입니까? 사전이 깔끔한 트릭이기 때문에 전체 리스너 스레드가 아니라 전역 변수를 응축하는 것 같습니다. –

+0

그래, 그게 정확히 제가 생각한 것입니다! –