Python设计模式 专题
您的位置:python > Python设计模式专题 > Python并发(多线程)
Python并发(多线程)
作者:--    发布时间:2019-11-20

并发性常常被误解为并行性。 并发意味着调度独立代码以系统方式执行。 本章重点介绍使用python的操作系统的并发执行。

以下程序实现执行操作系统的并发性 -

import os
import time
import threading
import multiprocessing

num_workers = 4

def only_sleep():
   print("pid: %s, process name: %s, thread name: %s" % (
      os.getpid(),
      multiprocessing.current_process().name,
      threading.current_thread().name)
   )
   time.sleep(1)

def crunch_numbers():
   print("pid: %s, process name: %s, thread name: %s" % (
      os.getpid(),
      multiprocessing.current_process().name,
      threading.current_thread().name)
   )
   x = 0
   while x < 10000000:
      x += 1
for _ in range(num_workers):
   only_sleep()
end_time = time.time()
print("serial time=", end_time - start_time)

# run tasks using threads
start_time = time.time()
threads = [threading.thread(target=only_sleep) for _ in range(num_workers)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
end_time = time.time()

print("threads time=", end_time - start_time)

# run tasks using processes
start_time = time.time()
processes = [multiprocessing.process(target=only_sleep()) for _ in range(num_workers)]
[process.start() for process in processes]
[process.join() for process in processes]
end_time = time.time()

print("parallel time=", end_time - start_time)

执行上述程序生成以下输出 -

说明
multiprocessing是一个类似于线程模块的包。 该软件包支持本地和远程并发。 由于这个模块,程序员可以在给定的系统上使用多个进程。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册