多线程基础——python

本文展示了Python中使用threading模块创建多线程的三种方法:1)直接通过`threading.Thread`创建;2)继承`threading.Thread`定义子类;3)使用锁机制确保线程同步;4)介绍了线程池的概念,强调了线程池在资源管理中的优势。

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

1、通过threading.Thread进行创建多线程,采用嵌套的方式(这里直接理解为了调用函数进行线程操作)

import threading
import time

#通过threading.Thread进行创建多线程
def target():
    print("the current threading %s is runing"
          % (threading.current_thread().name))
    time.sleep(1)
    print("the current threading %s is ended" % (threading.current_thread().name))


print("the current threading %s is runing" % (threading.current_thread().name))
## 属于线程t的部分
t = threading.Thread(target=target)
t.start()
## 属于线程t的部分
t.join()  # join是阻塞当前线程(此处的当前线程时主线程) 主线程直到Thread-1结束之后才结束
print("the current threading %s is ended" % (threading.current_thread().name))

输出结果:

the current threading MainThread is runing
the current threading Thread-1 is runing
the current threading Thread-1 is ended
the current threading MainThread is ended

2、#通过继承threading.Thread定义子类创建多线程。

例子:线程1和线程2交叉进行

import threading
import time
#通过继承threading.Thread定义子类创建多线程
class myThread(threading.Thread):  # 继承父类threading.Thread
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter

   def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
      print("Starting " + self.name)
      print_time(self.name, self.counter, 5)
      print("Exiting " + self.name)


def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print("%s process at: %s" % (threadName, time.ctime(time.time())))
      counter -= 1


# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启线程
thread1.start()
thread2.start()

# 等待线程结束
thread1.join()
thread2.join()

print("Exiting Main Thread")

输出结果:

Starting Thread-1
Starting Thread-2
Thread-1 process at: Sat Feb 18 20:56:01 2023
Thread-1 process at: Sat Feb 18 20:56:02 2023Thread-2 process at: Sat Feb 18 20:56:02 2023

Thread-1 process at: Sat Feb 18 20:56:03 2023
Thread-2 process at: Sat Feb 18 20:56:04 2023
Thread-1 process at: Sat Feb 18 20:56:04 2023
Thread-1 process at: Sat Feb 18 20:56:05 2023
Exiting Thread-1
Thread-2 process at: Sat Feb 18 20:56:06 2023
Thread-2 process at: Sat Feb 18 20:56:08 2023
Thread-2 process at: Sat Feb 18 20:56:10 2023
Exiting Thread-2
Exiting Main Thread

3、为了防止线程1和线程2同时进行的过程中导致数据发生了改变。因此,通过locker类对其中一个线程进行加锁。

import threading
import time

#通过threadLock使得线程一个一个的进行
class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("Starting " + self.name)
        # 获得锁,成功获得锁定后返回True
        # 可选的timeout参数不填时将一直阻塞直到获得锁定
        # 否则超时后将返回False
        threadLock.acquire()
        print_time(self.name, self.counter, 5)
        # 释放锁
        threadLock.release()


def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
    t.join()

print("Exiting Main Thread")

输出结果:可以看到这里将线程1先运行完,然后运行线程2

Starting Thread-1
Starting Thread-2
Thread-1: Sat Feb 18 20:59:13 2023
Thread-1: Sat Feb 18 20:59:14 2023
Thread-1: Sat Feb 18 20:59:15 2023
Thread-1: Sat Feb 18 20:59:16 2023
Thread-1: Sat Feb 18 20:59:17 2023
Thread-2: Sat Feb 18 20:59:19 2023
Thread-2: Sat Feb 18 20:59:21 2023
Thread-2: Sat Feb 18 20:59:23 2023
Thread-2: Sat Feb 18 20:59:25 2023
Thread-2: Sat Feb 18 20:59:27 2023
Exiting Main Thread

4 线程池

传统多线程方案会使用“即时创建, 即时销毁”的策略。因此采用线程池的方式,线程创建后就全部放入线程池,然后一个一个处理里面的任务,最后进行销毁。

线程池数量:根据服务器CPU,看一个线程占用的百分比,剩下的等待时间的百分比就可以拿来添加多个线程。如果计算时间占50%, 等待时间50%,那么为了利用率达到最高,可以开2个线程。
本地计算时间为x,等待时间为y,则工作线程数(线程池线程数)设置为 N*(x+y)/x,能让CPU的利用率最大化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

今天不熬夜!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值