python - 执行队列中的函数

标签 python

我有一个例子,应该展示我想做的事情

queue = 2

def function():
    print 'abcd'
    time.sleep(3)

def exec_times(times):
    #do something
    function()

def exec_queue(queue):
    #do something
    function()

exec_times(3)
#things need be working while it waiting for the function finish
time.sleep(10)

结果应该是

abcd
abcd

#after finish the first two function executions
abcd

那么,有没有一种方法可以在不使用线程的情况下做到这一点?

我的意思是一些glib函数来完成这项工作。

最佳答案

如果您想避免线程,一种选择是使用多个进程。如果您使用的是 python 2.6,请查看 multiprocessing模块。如果是 python 2.5,请查看 pyprocessing .

注意多处理文档中的“Process Pools ”,它似乎可以满足您的要求:

One can create a pool of processes which will carry out tasks submitted to it with the Pool class.

class multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])

A process pool object which controls a pool of worker processes to which jobs can be submitted. It supports asynchronous results with timeouts and callbacks and has a parallel map implementation.

关于python - 执行队列中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276595/

相关文章:

python - 返回 peewee ORM 中分组项目的计数

python - 使用 SetParent win32gui 函数将 ffplay 窗口嵌入到 tkinter 框架中

python - 将 "collection"属性直接添加到类的顶层

python - 使用python替换所有换行符

python - 如何用python turtle画一个平铺的三角形

Python - 将列表的字典扁平化为唯一值?

python - Django:注释每个对象的重复值个数的计数

python - 如何将字节字符串的 Python 字符串表示形式转换为实际的字节字符串?

python - Pandas:追加现有的 CSV 文件、额外的列

python - 使用 icontains 的 Django SearchVector