Skip to main content
 首页 » 编程设计

python之同时在python中运行两行代码

2025年05月04日14jackei

如何在 Python 2.7 中同时运行两行代码?我认为它被称为并行处理或类似的东西,但我不太确定。

请您参考如下方法:

您可以使用多线程或多处理。

您将需要为任务使用队列。

下面的示例代码将帮助您开始使用多线程。

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 个线程来处理一个字符串。等待输入队列处理完毕,然后打印处理时间的输出。

您可以为不同类型的处理定义多个线程类。或者您将函数对象放入队列中,让不同的函数并行运行。