2014-04-19 4 views
0

파이썬에서 잠금 개체를 이해하려고합니다. 이를 위해 저는 python multithreading.Pool 객체와 같은 것을 프로그래밍했습니다. 그러나 나는 아직도 잠금이 다른 프로세스의 실행을 잠그지 않는 이유가 무엇인지 궁금해하고 있습니다. DoSomething (multiprocessing.Process) 클래스를 대체하면 : 클래스 DoSomething (threading.Thread)에 의해 : 이것은 완벽하게 작동합니다 (예외가없는 경우에만, 빈 목록에서 pop이 작동하지 않기 때문에). 그러나 나는 확신 할 수 없다. 이것은 자물쇠 때문이거나 공유 메모리 때문이다.파이썬 다중 스레드. 프로세스 잠금

#! /usr/bin/env python 

import multiprocessing, threading 

lock = multiprocessing.Lock() 

class DoSomething(multiprocessing.Process): 

    def __init__(self, jobList, lock): 
     super(DoSomething, self).__init__() 
     self.jobList, self.lock = jobList, lock 

    def run(self): 

     while jobList != []:    # while there're still jobs available 
      self.lock.acquire()   # lock the jobList 
      job = self.jobList.pop()  # and take the next job (in fact, pop removes the 
      print job      # lst object from the list and returns it). 
      self.lock.release()   # release the jobList, so that another thread may do another job 
      # do something with this job ... 

threads = [] 
jobList = [1,2,3,4] 
for i in range(4): 
    threads.append(DoSomething(jobList, lock)) 
    threads[-1].start() 

for t in threads: 
    t.join() 

이 프로그램의 출력은 : 로크 작동

$ python multThread.py 
4 
3 
2 
1 
4   // so it don't lock, we have calculated the job twice here! 
3 
2 
1 
// ... 

답변

1

. 문제은 멀티 프로세싱을 사용하는 경우 스레드가있는 것처럼 jobList이 공유 메모리에없는 것입니다. 다중 처리에서 별도의 프로세스에는 jobList 사본이 있습니다. jobListmultiprocessing.Array으로 만드십시오. 자세한 내용은 Sharing state between processes을 참조하십시오.

+0

나는 그것을 생각해야만했다. 목록을 manager = multiprocessing.Manager() 및 jobList = manager.list()로 변경하면 작동합니다. 감사 – quant

관련 문제