2

Python 2.3 是否有任何多处理类型模块?我被困在与我交互的程序中使用 2.3,并且希望能够设置一些多处理,因为我所做的任务只使用一个 CPU,而且效率非常低。

我希望每个线程/进程处理自己的全局变量,并且每个线程/进程不应与任何其他线程/进程共享任何变量。基本上我只想有一个需要通过函数运行的文件队列,每次运行都是一个全新的线程。

我试过使用thread.start_new_thread,但它只是把我的全局变量弄得一团糟。

我突然想到一个想法,我可以os.popen('python C:\function_dir\function.py vars...')从每个新线程中做一个吗?听起来很丑陋,但我不明白为什么它不起作用。os.popen在“线程”正确完成之前,主程序不会继续?

我可能会忽略任何想法或模块?

4

2 回答 2

0

我在任何地方都没有找到,我已经转向 python 2.5

于 2012-08-02T21:50:06.817 回答
0

使用线程。您只需要基于Thread构建一个类:

import threading

class myThread(threading.Thread):
    #
    # Constructor.
    #
    def __init__(self, ...):
        #
        # Call threading constructor.
        #
        threading.Thread.__init__(self)
        #
        # Your constructor code.
        #
        ...
    #
    # The code executed when starting the thread.
    #
    def run(self):
        ...
#
# Create an instance and start the thread.
#
myThread(...).start()

确保将所有变量保留在本地。如果您需要访问全局变量,请使用global语句:

counter = 0

class myThread(threading.Thread):
    ...
    def run(self):
        global counter
        ...
        counter = 17
...

对于锁定等,请查看 Python 文档:http ://docs.python.org/release/2.3.5/lib/module-threading.html

于 2012-12-10T15:34:21.753 回答