2013-11-28 36 views
0

如何在Python 2.7中同時運行兩行代碼?我認爲它被稱爲並行處理或類似的東西,但我不能太確定。我在這裏問,因爲我甚至不知道Google應該如何......因此,如果這是一個多餘的問題,我很抱歉。在python中同時運行兩行代碼?

在此先感謝!

+0

對於非實時操作系統,「完全相同的時間」是什麼? – alko

回答

3

您可以使用多線程或者多。

您將需要使用隊列執行任務。

下面的示例代碼將幫助您開始使用多線程。

import threading 
import Queue 
import datetime 
import time 

class myThread(threading.Thread): 
    def __init__(self, in_queue, out_queue): 
     threading.Thread.__init__(self) 
     self.in_queue = in_queue 
     self.out_queue = out_queue 

    def run(self): 
     while True: 
      item = self.in_queue.get() #blocking till something is available in the queue 
      #run your lines of code here 
      processed_data = item + str(datetime.now()) + 'Processed' 
      self.out_queue.put(processed_data) 


IN_QUEUE = Queue.Queue() 
OUT_QUEUE = Queue.Queue() 

#starting 10 threads to do your work in parallel 
for i in range(10): 
    t = myThread(IN_QUEUE, OUT_QUEUE) 
    t.setDaemon(True) 
    t.start() 

#now populate your input queue 
for i in range(3000): 
    IN_QUEUE.put("string to process") 

while not IN_QUEUE.empty(): 
    print "Data left to process - ", IN_QUEUE.qsize() 
    time.sleep(10) 

#finally printing output 
while not OUT_QUEUE.empty(): 
    print OUT_QUEUE.get() 

此腳本啓動10個線程來處理字符串。等待輸入隊列被處理,然後打印輸出和處理時間。

您可以爲不同類型的處理定義多個線程類。或者你將函數對象放在隊列中,並且有不同的函數並行運行。

+0

我喜歡這個例子。我認爲你的意思是'inserter'是它的'myThread'嗎? –

+0

亞..抱歉使用了舊的代碼片段,我有。忘了改變 – shshank

3

這取決於你在同一時間的意思。如果你想要的東西不會停止,而其他需要一段時間的東西運行,線程是一個體面的選擇。如果你想真正並行運行兩件事情,多處理是要走的路:http://docs.python.org/2/library/multiprocessing.html

0

有一個功能強大的軟件包可以使用python運行並行作業:使用JobLib

0

如果你的意思,例如啓動一個定時器,並開始一個循環,正是在那之後,我覺得你可以,你;這樣的:start_timer; start_loop在一行

+0

這是一樣的: 'start_timer \ n stop_timer' 但在一行;) –