2012-08-28 47 views
3

我編寫了示例程序。 它創建8個線程,而每一個使用多處理和線程技術的競爭條件

import threading 
from multiprocessing import Process 

def fast_function(): 
    pass 

def thread_function(): 
    process_number = 1 
    print 'start %s processes' % process_number 
    for i in range(process_number): 
     p = Process(target=fast_function, args=()) 
     p.start() 
     p.join() 

def main(): 
    threads_number = 8 
    print 'start %s threads' % threads_number 
    threads = [threading.Thread(target=thread_function, args=()) 
      for i in range(threads_number)] 

    for thread in threads: 
     thread.start() 

    for thread in threads: 
     thread.join() 

產卵過程中經常死機。與幾個例外這樣

Exception in thread Thread-3: 
Traceback (most recent call last): 
    File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner 
    self.run() 
    File "/usr/lib/python2.6/threading.py", line 484, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "./repeat_multiprocessing_bug.py", line 15, in thread_function 
    p.start() 
    File "/usr/lib/python2.6/multiprocessing/process.py", line 99, in start 
    _cleanup() 
    File "/usr/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup 
    if p._popen.poll() is not None: 
    File "/usr/lib/python2.6/multiprocessing/forking.py", line 106, in poll 
    pid, sts = os.waitpid(self.pid, flag) 
OSError: [Errno 10] No child processes 

Python版本2.6.5。有人可以解釋我做錯了什麼嗎?

+0

對於它的價值,它可以在'Windows'下使用'Python 2.6.4'以及使用'Python 2.7.2'的Linux下正常工作' –

回答

1

您可能試圖從交互式解釋器運行它。嘗試將代碼寫入文件並將其作爲python腳本運行,它可以在我的機器上運行...

請參閱Python multiprocessing docs上的說明和示例。

+0

我照你所描述的那樣工作,它不起作用。當線程和進程分開使用時,線程和進程會正常工作。 我目前的版本 - 這是Python中的錯誤 –