Python3多线程编程(学习笔记)

Python3多线程

多线程可以实现同时执行多个不同的程序,其具体应用有:

  1. 可将运行时间长的程序中的任务调度至后台处理;
  2. 在用户界面中,响应用户对某按钮触发事件的处理时,可以弹出进度条显示处理进度;
  3. 加快程序的运行速度;
  4. 在一些等待任务实现中,例如输入、文件读写、网络收发数据等,可以利用线程释放资源,如内存占用等。

Note:每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但线程必须依存在应用程序中,不可以独立执行,由应用程序提供多个线程执行控制。每个线程都有自己的一组CPU寄存器,称为线程的上下文,反映了线程上次运行该线程的CPU寄存器的状态。

指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。线程可以中断和暂时搁置(睡眠)

线程可以分为:

  • 内核线程
  • 用户线程

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

  • _thread
  • threading

     

使用Python线程

Python中使用线程有两种方式:

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

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

# function-线程函数
# args-传递给线程函数的参数,必须为tuple类型
# kwargs-可选参数

实例

#!/usr/bin/python3

import _thread
import time

#define a function for threads
def print_time( threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print ("%s: %s" % ( threadName, time.ctime(time.time())))

#Creat two threads
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: Wed Sep 12 22:55:59 2018
Thread-2: Wed Sep 12 22:56:01 2018
Thread-1: Wed Sep 12 22:56:01 2018
Thread-1: Wed Sep 12 22:56:03 2018
Thread-2: Wed Sep 12 22:56:05 2018
Thread-1: Wed Sep 12 22:56:05 2018
Thread-1: Wed Sep 12 22:56:07 2018
Thread-2: Wed Sep 12 22:56:09 2018
Thread-2: Wed Sep 12 22:56:13 2018
Thread-2: Wed Sep 12 22:56:17 2018

Note:请仔细分析该程序的执行逻辑。

Python3通过两个标准库_threadthreading提供对线程的支持。

_thread提供了低级别、原始的线程,相比于threading的功能比较有限。

threadingm模块还提供有如下方法:

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

线程模块提供了Thread类来处理线程:

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

使用threading模块创建线程

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

#!/usr/bin/python3

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("Start thread: " + self.name)
        print_time(self.name, self.counter, 5)
        print("Exit thread: " + 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

#Creat new thread
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

#Start new thread
thread1.start()
thread2.start()
thread1.join()  #Thread类中的join()方法等待至线程中止
thread2.join()

Note:Python命名规范:

Python的命名非常重要,若命名不规范或者冲突会造成错误。

  • 模块名:尽可能短、全小写命名。
  • 包名:同模块名。
  • 文件名:全小写,可用下划线。
  • 类名:首字母大写开头(Pascal命名风格)的规范:AdStats,ConfigUtil
Start thread: Thread-1
Start thread: Thread-2
Thread-1: Wed Sep 19 21:00:39 2018 
Thread-2: Wed Sep 19 21:00:40 2018 
Thread-1: Wed Sep 19 21:00:40 2018 
Thread-1: Wed Sep 19 21:00:41 2018 
Thread-2: Wed Sep 19 21:00:42 2018 
Thread-1: Wed Sep 19 21:00:42 2018 
Thread-1: Wed Sep 19 21:00:43 2018 
Exit thread: Thread-1
Thread-2: Wed Sep 19 21:00:44 2018 
Thread-2: Wed Sep 19 21:00:46 2018 
Thread-2: Wed Sep 19 21:00:48 2018 
Exit thread: Thread-2

Process finished with exit code 0

 线程同步

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

使用Thread对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire方法和release方法,用于那些需要每次只允许一个线程操作的数据。例如,一个列表中所有元素为0,线程“set”从后向前修改元素为1,线程“print”从前向后读取列表并打印。可能“set”开始执行时“print”已在打印列表元素,输出部分为0部分为1的情况。因此引入锁的概念。

锁有两种状态——锁定和未锁定。

每当一个线程比如"set"要访问共享数据时,必须先获得锁定;如果已经有别的线程比如"print"获得锁定了,那么就让线程"set"暂停,也就是同步阻塞;等到线程"print"访问完毕,释放锁以后,再让线程"set"继续。

经过这样的处理,打印列表时要么全部输出0,要么全部输出1,不会再出现一半0一半1的尴尬场面。

#!/usr/bin/python3

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("Start thread: " + 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("Exit main thread!")

Start thread: Thread-1
Start thread: Thread-2
Thread-1: Wed Sep 19 21:24:18 2018
Thread-1: Wed Sep 19 21:24:19 2018
Thread-1: Wed Sep 19 21:24:20 2018
Thread-2: Wed Sep 19 21:24:22 2018
Thread-2: Wed Sep 19 21:24:24 2018
Thread-2: Wed Sep 19 21:24:26 2018
Exit main thread!

线程优先级队列(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() 实际上意味着等到队列为空,再执行别的操作
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Created by Lu Zhan
# 09/26/2018

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("Starting " + self.name)
        process_data(self.name, self.q)
        print("Exiting " + 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)     #Constructor for a FIFO queue
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("Exiting Main Thread!")


————————————————————————————————————————————————————————————————————————————
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-2
Exiting Thread-1

Exiting Main Thread!

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值