Python中的多线程和多进程处理函数
Python是一种解释型语言,在单线程下一次只能执行一个任务。然而,在某些情况下,我们需要同时处理多个任务,这时候就需要用到多线程和多进程处理函数。本文将对Python中的多线程和多进程处理函数进行介绍。
一、多线程
多线程是指在同一程序中运行多个线程,每个线程都可以执行不同的任务。多线程可以提高程序的运行效率,提高系统资源的利用率。Python中的多线程实现非常简单,主要有两种方式:使用_thread模块和使用threading模块。
1.使用_thread模块
主要使用_thread.start_new_thread()函数来实现多线程。_thread.start_new_thread()函数需要多传入一个函数名和一个参数列表,相当于启动一个新的线程。
示例代码:
import _thread
import time
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % ( threadName, time.ctime(time.time()) ))
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print("Error: 无法启动线程")
while 1:
pass
运行代码后,可以看到程序同时启动了两个线程,每个线程会执行5次print_time函数,每次执行间隔2秒或4秒。
2.使用threading模块
使用threading模块可以更方便地创建和管理线程。通过创建Thread类的实例来创建线程,必须传入一个函数名作为参数。使用start()方法来启动线程。
示例代码:
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print ("开始线程:" + self.name)
print_time(self.name, self.delay, 5)
print ("退出线程:" + self.name)
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# 创建新线程
thread1 = myThread(1, "Thread-1", 2)
thread2 = myThread(2, "Thread-2", 4)
# 开启新线程
thread1.start()
thread2.start()
print ("退出主线程")
运行代码后,可以看到程序同时启动了两个线程,每个线程会执行5次print_time函数,每次执行间隔2秒或4秒。
二、多进程
多进程是指在同一程序中运行多个进程,每个进程相互独立,每个进程都可以执行不同的任务。多进程可以提高程序的运行效率,提高系统资源的利用率。Python中的多进程实现非常简单,主要有两种方式:使用multiprocessing模块和使用os模块。
1.使用multiprocessing模块
使用multiprocessing模块可以更方便地创建和管理进程。通过创建Process类的实例来创建进程,必须传入一个函数名作为参数。使用start()方法来启动进程。
示例代码:
import multiprocessing
import time
def print_time(processName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % ( processName, time.ctime(time.time()) ))
if __name__ == '__main__':
# 创建新进程
process1 = multiprocessing.Process(target=print_time, args=("Process-1", 2))
process2 = multiprocessing.Process(target=print_time, args=("Process-2", 4))
# 开启新进程
process1.start()
process2.start()
# 等待进程执行完成
process1.join()
process2.join()
print("退出主进程")
运行代码后,可以看到程序同时启动了两个进程,每个进程会执行5次print_time函数,每次执行间隔2秒或4秒。
2.使用os模块
使用os模块可以更底层地创建和管理进程。使用os.fork()函数可以创建子进程。
示例代码:
import os
import time
def print_time(processName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % ( processName, time.ctime(time.time()) ))
pid = os.fork()
if pid == 0:
print_time("子进程", 2)
else:
print_time("父进程", 4)
print("退出主进程")
运行代码后,可以看到程序同时启动了两个进程,每个进程会执行5次print_time函数,每次执行间隔2秒或4秒。
总结
多线程和多进程都是提高程序运行效率的有效手段。多线程适合于I/O密集型任务,可以有效解决阻塞问题;多进程适合于CPU密集型任务,可以充分利用多核CPU资源。在选择多线程或多进程时,要根据实际情况进行综合考虑,选择最适合的方式。
