2012-08-28 48 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中的错误 –