python 多线程并发实例,Python并发(多线程)

本篇文章帮大家学习python并发(多线程),包含了Python并发(多线程)使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。

并发性常常被误解为并行性。 并发意味着调度独立代码以系统方式执行。 本章重点介绍使用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是一个类似于线程模块的包。 该软件包支持本地和远程并发。 由于这个模块,程序员可以在给定的系统上使用多个进程。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值