日常运维中,经常需要并发来提升工作效率。Python提供了多线程和多进程两种方式。

import time
import threading
import multiprocessing

def print_fun(num):
print(time.strftime('%Y-%m-%d %H:%M:%S'),num,"begin")
time.sleep(2)
print(time.strftime('%Y-%m-%d %H:%M:%S'),num,"------end")


def mutil_thread():
print("\n多线程模式")
threads = []
for i in range(5):
num = str(i)
t = threading.Thread(target=print_fun,args=(num))
threads.append(t)

for x in threads:
x.start()
for x in threads:
x.join()

def mutil_process():
print("\n多进程模式")
threads = []
for i in range(5):
num = str(i)
t = multiprocessing.Process(target=print_fun,args=(num))
threads.append(t)

for x in threads:
x.start()
for x in threads:
x.join()

if __name__ == '__main__':
mutil_thread()
mutil_process()
[root@test1 dataC]# python3 test.py 

多线程模式
2022-11-26 20:41:17 0 begin
2022-11-26 20:41:17 1 begin
2022-11-26 20:41:17 3 begin
2022-11-26 20:41:17 2 begin
2022-11-26 20:41:17 4 begin
2022-11-26 20:41:19 0 ------end
2022-11-26 20:41:19 2 ------end
2022-11-26 20:41:19 4 ------end
2022-11-26 20:41:19 3 ------end
2022-11-26 20:41:19 1 ------end

多进程模式
2022-11-26 20:41:19 0 begin
2022-11-26 20:41:19 3 begin
2022-11-26 20:41:19 1 begin
2022-11-26 20:41:19 4 begin
2022-11-26 20:41:19 2 begin
2022-11-26 20:41:21 0 ------end
2022-11-26 20:41:21 3 ------end
2022-11-26 20:41:21 1 ------end
2022-11-26 20:41:21 2 ------end
2022-11-26 20:41:21 4 ------end