[Python] (Day-23) - 多线程

作者: 已重置2020 | 来源:发表于2017-11-30 11:47 被阅读28次
If you shut the door to all errors, truth will be shut out. 你如果拒绝面对错误,真相也会被挡在门外。

多线程类似于同时执行多个不同程序,多线程运行有如下优点:

  • 使用线程可以把占据长时间的程序中的任务放到后台去处理
  • 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
  • 程序的运行速度可能加快
  • 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等

线程和进程

  • 每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口
  • 线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。

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


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

  • _thread
  • threading (推荐使用)

_thread 的简单使用

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

函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:

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

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。
# 引入线程模块
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

输出结果:

Thread-1: Tue Nov 28 17:26:46 2017
Thread-2: Tue Nov 28 17:26:48 2017
Thread-1: Tue Nov 28 17:26:48 2017
Thread-1: Tue Nov 28 17:26:50 2017
Thread-2: Tue Nov 28 17:26:52 2017
Thread-1: Tue Nov 28 17:26:52 2017
Thread-1: Tue Nov 28 17:26:54 2017
Thread-2: Tue Nov 28 17:26:56 2017
Thread-2: Tue Nov 28 17:27:00 2017
Thread-2: Tue Nov 28 17:27:04 2017

总结:线程1 和线程2 都在运行


threading 的简单使用

_thread提供了低级别的、原始的线程以及一个简单的锁,它相比于threading` 模块的功能还是比较有限的。

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

  • threading.currentThread(): 返回当前的线程变量。
  • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
  • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

  • run(): 用以表示线程活动的方法。
  • start():启动线程活动。
  • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  • isAlive(): 返回线程是否活动的。
  • getName(): 返回线程名。
  • setName(): 设置线程名。
使用 threading 模块创建线程

我们可以通过直接从 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
    
    # threading自带函数,用以表示线程活动的方法
    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()
# 等待至线程中止
thread2.join()
thread1.join()
# 所有线程结束,后执行此操作
print ("退出主线程")

输出结果:

开始线程:Thread-1
开始线程:Thread-2
Thread-1: Tue Nov 28 17:33:22 2017
Thread-1: Tue Nov 28 17:33:23 2017
Thread-2: Tue Nov 28 17:33:23 2017
Thread-1: Tue Nov 28 17:33:24 2017
Thread-1: Tue Nov 28 17:33:25 2017
Thread-2: Tue Nov 28 17:33:25 2017
Thread-1: Tue Nov 28 17:33:26 2017
退出线程:Thread-1
Thread-2: Tue Nov 28 17:33:27 2017
Thread-2: Tue Nov 28 17:33:29 2017
Thread-2: Tue Nov 28 17:33:31 2017
退出线程:Thread-2
退出主线程

总结:执行 start() 方法开启线程;执行 exit()方法退出线程;执行 join() 加入线程池,等待其完成后,执行后续操作。


线程同步

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

线程锁(互斥锁Mutex)

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

不使用线程同步(不加锁)

示例:

import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

输出结果:我这里是8, 不同的机器输出不一样,结果不固定

-8
使用线程同步(加锁)
import time, threading

# 假定这是你的银行存款:
balance = 0
# 定义锁对象
lock = threading.Lock()

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        # 先要获取锁:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了释放锁:
            lock.release()

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

输出结果永远是 0


Semaphore(信号量)

互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据

import threading,time
 
def run(n):
    semaphore.acquire()
    time.sleep(1)
    print("run the thread: %s\n" %n)
    semaphore.release()
 
if __name__ == '__main__':
 
    num= 0
    semaphore  = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
    for i in range(20):
        t = threading.Thread(target=run,args=(i,))
        t.start()
 
while threading.active_count() != 1:
    pass #print threading.active_count()
else:
    print('----all threads done---')
    print(num)

run the thread: 4
run the thread: 2
run the thread: 3
run the thread: 0
run the thread: 1

run the thread: 5
run the thread: 9
run the thread: 8
run the thread: 6
run the thread: 7

run the thread: 11
run the thread: 13
run the thread: 10
run the thread: 12
run the thread: 14

run the thread: 15
run the thread: 19
run the thread: 17
run the thread: 18
run the thread: 16

----all threads done---
0

总结:每次开启五个线程,顺序随机

PS: BoundedSemaphore() 改成 1,就变成了单线程,顺序执行


Timer

让一个方法在子线程里延迟执行,time.sleep() 是在主线程睡眠

代码示例:

import threading

def hello():
    print("hello, world")

t = threading.Timer(30.0, hello)
t.start()

# 30 秒后, "hello, world" 将会被打印

线程优先级队列( Queue)

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue

Queue 模块中的常用方法:

  • Queue.qsize() 返回队列的大小
  • Queue.empty() 如果队列为空,返回True,反之False
  • Queue.full() 如果队列满了,返回True,反之False
  • Queue.full 与 maxsize 大小对应
  • Queue.get([block[, timeout]])获取队列,timeout等待时间
  • Queue.get_nowait() 相当Queue.get(False)
  • Queue.put(item) 写入队列,timeout等待时间
  • Queue.put_nowait(item) 相当Queue.put(item, False)
  • Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
  • Queue.join() 实际上意味着等到队列为空,再执行别的操作

实例:


import queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):

    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print ("开启线程:" + self.name)
        process_data(self.name, self.q)
        print ("退出线程:" + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print ("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")

输出结果:

开启线程:Thread-1
开启线程:Thread-2
开启线程:Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
退出线程:Thread-3
退出线程:Thread-2
退出线程:Thread-1
退出主线程

总结:使用队列后, 线程是先进后出,即:LIFO

相关文章

  • [Python] (Day-23) - 多线程

    多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理 用...

  • GIL

    谈谈python的GIL、多线程、多进程 最近在看 Python 的多线程,经常我们会听到老手说:“python下...

  • Python多线程编程——多线程编程中的加锁机制

    如果大家对Python中的多线程编程不是很了解,推荐大家阅读之前的两篇文章:Python多线程编程——多线程基础介...

  • 5-线程(补充)

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python_提高

    GIL全局解释器锁 描述Python GIL的概念, 以及它对python多线程的影响?编写⼀个 多线程抓取⽹⻚的...

  • Python程序员都知道的入门知识の八

    目录【Python程序员都知道的入门知识】 1. 多线程threading、Queue Python的多线程由th...

  • Python多线程实现生产者消费者

    1. Python多线程介绍 Python提供了两个有关多线程的标准库,thread和threading。thre...

  • 多线程

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python多线程(上)

    前言 说起Python的多线程,很多人都嗤之以鼻,说Python的多线程是假的多线程,没有用,或者说不好用,那本次...

  • Python 3中的多线程

    Python 3的多线程 Python 3的多线程模块threading在旧版_thread模块基础上进行了更高层...

网友评论

    本文标题:[Python] (Day-23) - 多线程

    本文链接:https://www.haomeiwen.com/subject/gwcvbxtx.html