2013-11-28 40 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' 但在一行;) –