2010-07-18 27 views
1

我有一個例子執行功能誰應該表現出我想要做的在隊列

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 

如此,還有一個辦法做到這一點不使用trhead?

我的意思是一些glib函數來完成這項工作。

+1

您需要有某種線程/多進程模型才能併發執行。 – 2010-07-18 17:55:56

回答

2

如果你想避免線程,一個選項是使用多個進程。如果你使用python 2.6,請看multiprocessing模塊。如果是python 2.5,請看pyprocessing

在文檔的多,這似乎處理您的要求

注「Process Pools」:

可以創建的,將進行提交,以使其與池類任務的進程池中。

類multiprocessing.Pool([工序[,初始化[,initargs [,maxtasksperchild]]]])

,其控制工作進程池中的進程池中對象的作業 可以提交。它支持異步結果與超時回調 並具有並行地圖實施。

+0

我想像glib.timeout_add(間隔,回調,...)而不是每間隔執行函數,它會繼續觀看函數,直到它完成,然後調用回調。 感謝您的回覆 – killown 2010-07-18 18:12:55

+0

查看Process Pools - 查看我的答案中的更新。 – ars 2010-07-18 18:39:43

+0

請注意,參數maxtasksperchild僅在Python 2.7中可用 – 2011-11-24 12:07:55