线程中的Python异常:无法启动新线程

时间:2018-05-16 10:49:16

标签: python multithreading python-2.7 queue

我正在尝试运行我正在使用Queue和线程的代码。 以下是代码段:

import threading
from Queue import Queue


def function():
    results = []
    for i in range(68):
        return_list = function2(i)
        results.append(return_list)
        if return_list:
            print("True returned")
        else:
            print("Returned false")
    return results


def function2(i):
    print("In function 2 with: " + str(i))
    results = []
    working_queue = Queue()
    for _ in range(25):
        worker = threading.Thread(target=function3, args=(working_queue, results))
        worker.setDaemon(True)
        worker.start()

    for p in range(150):
        working_queue.put(p)

    working_queue.join()
    return results


def function3(working_queue, results):
    while True:
        try:
            current_item = working_queue.get()
            print("Processing:" + str(current_item))
            results.append("True")
        except Exception as e:
            print("An exception in function 3: " + str(e))
        finally:
            working_queue.task_done()

if __name__ == "__main__":
    results = function()
    print(str(results))

代码引发以下异常:

Traceback (most recent call last):
File "C:/pythonErrors/stackoverflow.py", line 45, in <module>
    function()
File "C:/pythonErrors/stackoverflow.py", line 8, in function
    return_list = function2(i)
File "C:/pythonErrors/stackoverflow.py", line 24, in function2
    worker.start()
File "C:\Python27\lib\threading.py", line 736, in start
    _start_new_thread(self.__bootstrap, ())
thread.error: can't start new thread

我们如何删除以前创建和完成的线程。因此,在function2()中执行每个for循环执行时,不会创建新线程 要求是为整个过程只创建25个线程(目前总共创建了68x25个线程)

1 个答案:

答案 0 :(得分:1)

因为,要求总共使用25个线程;线程的创建应该是最外层函数的一部分(即函数())。 以下是解决方案:

import threading
from Queue import Queue


def function():
    results = []
    working_queue = Queue()
    for _ in range(25):
        worker = threading.Thread(target=function3, args=(working_queue, results))
        worker.setDaemon(True)
        worker.start()
    for i in range(68):
        return_list = function2(i, working_queue)
        working_queue.join()
        results.append(return_list)
        if return_list:
            print("True returned")
        else:
            print("Returned false")
    return results


def function2(i, working_queue):
    print("In function 2 with: " + str(i))
    for p in range(150):
        working_queue.put(p)


def function3(working_queue, results):
    while True:
        try:
            current_item = working_queue.get()
            print("Processing:" + str(current_item))
            results.append("True")
        except Exception as e:
            print("An exception in function 3: " + str(e))
        finally:
            working_queue.task_done()


if __name__ == "__main__":
    results = function()
    print(str(results))