Python Design Patterns 简明教程
Concurrency in Python
并发经常被误解为并行。并发意味着以系统化的方式计划执行独立的代码。本章重点介绍使用 Python 为操作系统执行并发性。
Concurrency is often misunderstood as parallelism. Concurrency implies scheduling independent code to be executed in a systematic manner. This chapter focuses on the execution of concurrency for an operating system using Python.
以下程序有助于为操作系统执行并发性−
The following program helps in the execution of concurrency for an operating system −
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)
Explanation
“multiprocessing”是一个类似于 threading 模块的包。该包支持本地和远程并发。由于该模块,程序员可以利用给定系统上的多个进程。
“multiprocessing” is a package similar to the threading module. This package supports local and remote concurrency. Due to this module, programmers get the advantage to use multiple processes on the given system.