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。有人可以解释我做错了什么吗?

4

2 回答 2

1

多处理模块在 2.6.5 中存在线程安全问题。您最好的选择是更新到更新的 Python,或者将此补丁添加到 2.6.5:http ://hg.python.org/cpython/rev/41aef062d529/

该错误在以下链接中进行了更详细的描述:

于 2012-10-30T16:15:38.270 回答
1

您可能正在尝试从交互式解释器中运行它。尝试将代码写入文件并将其作为 python 脚本运行,它可以在我的机器上运行...

请参阅Python 多处理文档中的说明和示例。

于 2012-08-28T12:49:07.847 回答