python3多线程

Python中的多线程由于GIL无法并行执行CPU密集型任务,但在I/O密集型任务中有用。标准库中的队列不支持线程优先级,若要实现需自定义机制。可通过`Queue`对象获取多线程函数的返回值,示例中展示了如何使用队列收集并打印线程计算结果。注意线程调度的不确定性可能导致结果顺序不固定。
摘要由CSDN通过智能技术生成

在Python中,由于全局解释器锁(GIL)的存在,多线程并不能真正并行执行Python代码,但是它们可以用于I/O密集型任务,如文件读写、网络通信等。

创建线程

线程方法

● _thread模块

_thread.start_new_thread ( function, args[, kwargs] )

threading 模块

比_thread模块多出的方法:

● threading. current_thread(): 返回当前的线程变量。

● threading.enumerate(): 返回一个包含正在运行的线程的列表。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。

● threading.active_count(): 返回正在运行的线程数量,与 len(threading.enumerate()) 有相同的结果。

● threading.Thread(target, args=(), kwargs={}, daemon=None):

1.使用 threading 模块创建线程

通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法:

import threading

class myThread (threading.Thread):

    def __init__(self, threadID, name, delay):        threading.Thread.__init__(self)//必须的

  def run(self):

        .....

# 创建新线程

thread1 = myThread(1, "Thread-1", 1)

thread2 = myThread(2, "Thread-

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

test猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值