Python3 多线程

线程

线程(thread [θred] )是操作系统能够进行运算调度的最小单位。他包含在进程中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

Threading

thread模块已被废弃,可以使用threading模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 "_thread"。

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

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。

threading 模块提供的方法:

  • threading.currentThread(): 返回当前的线程变量。
  • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
  • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
  • Thread类来处理线程
    • run(): 用以表示线程活动的方法。
    • start():启动线程活动
    • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
    • isAlive(): 返回线程是否活动的。
    • getName(): 返回线程名。
    • setName(): 设置线程名。

线程同步

如果俩个线程对共同的数据进行修改就需要使用到线程同步。
这里要使用到锁的概念。锁,简单来讲就是将同用数据锁定,关小黑屋。

使用acquire [əˈkwaɪər](关锁),release[rɪˈliːs](开锁)

#!/usr/bin/python3

import threading
import time

class myThread (threading.Thread): #继承Thread
    def __init__(self, threadID, name, counter): #初始化
        threading.Thread.__init__(self) #调用父类初始化
        self.threadID = threadID  # 线程ID
        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 ("退出主线程")

 

posted @ 2021-12-12 13:25  老徐-lex  阅读(196)  评论(0编辑  收藏  举报