Python3 多线程

Python3 中线程常用的两个模块为:

  • _thread
  • threeading

thread 模块已经废弃,在 Python3 中使用 threading 模块代替。(因为兼容性,Python3 将 thread 重命名为 _thread )

使用线程的两种方式:

  1. 函数
  2. 用类包装线程对象

函数

调用 _thread 模块中的 start_new_thread() 函数来产生新线程。

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

参数说明:

  • function —— 线程函数
  • args —— 传递给线程函数的参数,它必须是个 tuple 类型
  • kwargs —— 可选参数
#! /usr/bin/env python3
# 用来指定本脚本用什么解释器来执行

import _thread
import time

# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s: %s" %(threadName, time.ctime(time.time()) ) )

# 创建两个线程
try:
    _thread.start_new_thread(print_time, ("Thread-1", 2, ) )
    _thread.start_new_thread(print_time, ("Thread-2", 4, ) )
except:
    print("Error: 无法启动线程")

while 1:
    pass

类包装线程

threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:

  • threading.currentThread() : 返回当前的线程变量
  • threading.enumerate() : 返回一个包含正在运行的线程的 list
  • threading.activeCount : 返回正在运行的线程数量

提供了 Thread 类来处理线程,Thread 类提供了以下方法:

  • run() : 表示线程活动
  • start() : 启动线程
  • join([time]) : 等待至线程中止
  • isAlive() : 返回线程是否活动的
  • getName() : 返回线程名
  • setName() : 设置线程名

从 threading.Thread 继承创建一个新的子类,实例化后调用 start() 方法启动新线程,调用线程的run()方法。

import threading
import time

exitFlag = 0

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("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print("退出线程: " + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print("%s: %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("退出主线程")

线程同步

如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。

使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放在 acquire 和 release 方法之间。

import threading
import time

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("开启线程:" + self.name)
        # 获取锁,用于线程同步
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 释放锁, 开启下一个线程
        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("退出主线程")

参考:https://www.runoob.com/python3/python3-multithreading.html

原文地址:https://www.cnblogs.com/augustine0654/p/15154274.html