Python多线程入门学习
作者:Python程序u猿 发布时间:2021-10-11 00:26:09
Python 中使用线程有两种方式:函数或者用类来包装线程对象。
函数式:
调用 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: unable to start thread")
while 1:
pass
使用 Threading 模块创建线程
使用 Threading
模块创建线程,直接从 threading.Thread
继承,然后重写__init__
方法和 run
方法:
import threading
import time
exitFlag = 0
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:
if exitFlag:
(threading.Thread).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()
print ("Exiting Main Thread")
线程同步
如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。
使用 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 ("Starting " + self.name)
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
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 ("Exiting 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() 实际上意味着等到队列为空,再执行别的操作
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)
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")
来源:https://blog.csdn.net/Python_222/article/details/121772468
猜你喜欢
- PyType_Type和PyBaseObject_TypePyObject和PyTypeObject内容的最后指出下图中对实例对象和类型对象
- 增大 SGA 已经缓冲看来对于性能的提升并不显著,加载时间只提升了 1.73%。下面我们增加 SGA 重做日志的大小: DB3: Log B
- 下面给大家介绍下pandas读取CSV文件时查看修改各列的数据类型格式,具体内容如下所述:我们在调bug的时候会经常查看、修改pandas列
- 本文实例讲述了php常用字符串长度函数strlen()与mb_strlen()用法。分享给大家供大家参考,具体如下:int strlen (
- 这可是个综合性的问题,看看下面对文件操作的集大成代码:<% 'Set file i/
- 对于编译型的语言,比如C#中的一个.cs文件,Java中的一个.java或者编译后的.class文件可以认为是一个模块(但常常不表述为模块)
- 这篇论坛文章主要介绍了Oracle数据库到SQL Server数据库主键的迁移过程,具体内容请参考下文。由于项目需要要将以前Oracle的数
- 布尔表示两值之一:True 或 False。 布尔值在编程中,通常需要知道表达式是 True 还是 False。可以计算 Python 中的
- 1.语法及用法(1)语法:str.endswith(suffix[,start][,end])str:字符串,待判断字符串suffix:后缀
- 支付宝lab的意思是支付宝实验室,也就是概念产品聚集地,可以让用户快速试用这些新产品。本次支付宝lab logo设计历时一个星期,视觉设计组
- 清除视图缓存,就是清除D:\phpStudy\WWW\BCCKidV1.0\storage\framework\views\002f30b1
- ----------记录一下这两天做的一个小demo功能是要实现一个从前端传给后端一张图片,在后端完成目标检测后,传给前端,前端接收后并展示
- 本文实例讲述了JS实现合并json对象的方法。分享给大家供大家参考,具体如下:一、问题:求json对象合并的方法var a ={"
- 训练完目标检测模型之后,需要评价其性能,在不同的阈值下的准确度是多少,有没有漏检,在这里基于IoU(Intersection over Un
- 一、抓取全部评论吾的这篇文章,有 1022 次评论,一条条看,吾看不过来,于是想到 Python 词云,提取关键词,倒也是一桩趣
- PHP页面中如果不希望出现以下情况: 单引号被转义为 \' 双引号被转义为 \" 那么可以进行如下设置以防止: 方法一:在
- 大家一定使用过 phpmyadmin 里面的数据库导入,导出功能,非常方便。但是在实际应用中,我发现如下几个问题: 1、数据库超过一定尺寸,
- 在上一篇文章中 ,我说到:强硬的把CSS和HTML塞到PHP里面可以防止代码太枯燥(DRY)并最终导致代码臃肿,因为的CSS和HTML需要比
- 由于网络带宽以及某些WAP服务器DECK传输的限制,所以DECK越小越好,最好不要超过1.2K。如果你的需求很复杂,最好分成几个DECK来完
- 一、picklepickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件。&n