Python3 多任务之---线程

本文深入探讨了Python中多线程编程的多种实现方法,包括使用threading模块的基础线程操作,通过继承Thread类定制线程行为,以及利用互斥锁、队列和全局变量进行线程间的同步和通信。此外,还介绍了生产者与消费者模式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多线程 threading 模块

  • 方式一
import threading    #或from threading import Thread
import time

def test():
    print('线程输出……')
    time.sleep(1)

if __name__ == '__main__':
    for i in range(5):
        t = threading.Thread(target=test)
        t.start()
  • 方式二:继承类的方法
import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm"+self.name+' @ '+str(i)    #name 中保存的是当前线程名字
            print(msg)

def test():
    for i in range(5):
        t = MyThread()
        t.start()

if __name__ == '__main__':
    test()
  • 线程共享全局变量:global

互斥锁

  • 创建锁(默认不上锁)

    mutex = threading.Lock()
  • 锁定

    mutex.acquire([blocking])
  • 释放

    mutex.release()
  • 上锁代码,越少越好

避免死锁

  • 程序设计时要尽量避免(银行家算法)
  • 添加超时时间等(mutex.acquire(timeout=2))

生产者与消费者模式

  • 进程间使用队列
from queue import Queue
queue = Queue()
queue.put('添加')
queue.get()    #获取队列数据
queue.qsize()  #队列大小
import threading
from queue import Queue
import time

class A(threading.Thread):
    def run(self):
        global queue
        while True:
            if queue.qsize()<=50:
                for i in range(100):
                    queue.put('产品'+str(i))
                    print(self.name+'生产产品'+str(i))
                    time.sleep(0.2)

class B(threading.Thread):
    def run(self):
        global queue
        while True:
            if queue.qsize() >= 50:
                for i in range(10):
                    q = queue.get()
                    print(self.name+'消费'+q)
                    time.sleep(0.5)
                
queue = Queue()
for i in range(10):
    queue.put('初始产品'+str(i))

for i in range(2):
    a = A()
    a.start()

for i in range(5):
    b = B()
    b.start()

全局字典

global_dict = {}

def std_thread(name):
    std = Student(name)
    global_dict[threading.current_thread()] = std
    do_task_1()
    do_task_2()

def do_task_1():
    std = global_dict[threading.current_thread()]
    ……

def do_task_2():
    std = global_dict[threading.current_thread()]
    ……

ThreadLocal 方式

import threading

local_school = threading.local()

def process_student():
    std = local_school.student
    print('hello,%s(in %s)'%(std,threading.current_thread().name))

def process_thread(name):
    local_school.student = name
    process_student()

t1 = threading.Thread(target=process_thread,args=('dongGe',),name='Thread-A')
t1 = threading.Thread(target=process_thread,args=('老王',),name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值