一:python多线程优点
python多线程在实际项目编程中比较常用,其主要有以下优点:
1.使用线程可以把占据长时间的程序中的任务放到后台去处理。
2. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
3. 程序的运行速度可能加快
4. 在一些需要阻塞的任务,如等待用户输入、文件读写和网络收发数据等,释放一些珍贵的资源如内存占用等等。
二:python多线程编程方法
1.使用_thread(python3.x)或者thread(python2.x)模块里的函数
2.使用threading模块里的类
以上两种方法在python的标准库均支持,不过因为python版本的兼容性问题,建议使用第二种方法,通过创建类实例方法进行多线程编程
三:使用_thread模块创建线程,实例如下:
#使用_thread模块调用函数来使用多线程(这里使用_thread是因为python版本为3.x, 2.x的版本使用thread)
import _thread
import time
#定义线程回调函数
def print_time(threadName, delay):
count = 0
while count < 3:
time.sleep(delay)
count += 1
print("%s: %s" % (threadName, time.ctime(time.time())))
#创建两个线程
try:
_thread.start_new_thread(print_time, ("thread1", 1))
_thread.start_new_thread(print_time, ("thread2", 2))
except:
print("Error: unable to start thread")
while 1:
pass
运行结果:
thread1: Fri Jan 31 13:40:48 2020
thread2: Fri Jan 31 13:40:49 2020
thread1: Fri Jan 31 13:40:49 2020
thread1: Fri Jan 31 13:40:50 2020
thread2: Fri Jan 31 13:40:51 2020
thread2: Fri Jan 31 13:40:53 2020
四:使用Threading模块创建线程,实例如下
import threading
import time
#继承父类threading.Thread
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): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
print ("Starting: " + self.name)
print_time(self.name, 3, self.counter)
print ("Exiting: " + self.name)
def print_time(threadName, delay, counter):
while counter:
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
time.sleep(delay)
# 创建新线程
thread1 = myThread(1, "thread1", 3)
thread2 = myThread(2, "thread2", 3)
# 开启线程
thread1.start()
thread2.start()
print ("Exiting Main Thread")
运行结果:
Starting: thread1
thread1: Fri Jan 31 13:55:12 2020
Starting: thread2
Exiting Main Thread
thread2: Fri Jan 31 13:55:12 2020
thread1: Fri Jan 31 13:55:15 2020
thread2: Fri Jan 31 13:55:15 2020
thread1: Fri Jan 31 13:55:18 2020
thread2: Fri Jan 31 13:55:18 2020
Exiting: thread1
Exiting: thread2
五:线程同步
线程同步的好处是访问共享数据时,通过加锁和解锁方式使用共享数据,保证数据的正确性,举个栗子:每当一个线程比如"set"要访问共享数据时,必须先获得锁定;如果已经有别的线程比如"print"获得锁定了,那么就让线程"set"暂停,也就是同步阻塞;等到线程"print"访问完毕,释放锁以后,再让线程"set"继续。
经过这样的处理,打印列表时要么全部输出0,要么全部输出1,不会再出现一半0一半1的尴尬场面。
实例如下:
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, 2, self.counter)
# 释放锁
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, "thread1", 2)
thread2 = myThread(2, "thread2", 3)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print ("Exiting Main Thread")
运行结果:
thread1: Fri Jan 31 14:09:43 2020
thread1: Fri Jan 31 14:09:45 2020
thread2: Fri Jan 31 14:09:47 2020
thread2: Fri Jan 31 14:09:49 2020
thread2: Fri Jan 31 14:09:51 2020
Exiting Main Thread
六:线程队列
Python提供了队列模块queue,可以使用队列来实现线程间的同步
以下为queue模块常见的使用:
函数 | 意义 |
---|---|
Queue.qsize() | 返回队列的大小 |
Queue.empty() | 如果队列为空,返回True,反之False |
Queue.full() | 如果队列满了,返回True,反之False |
Queue.full | 与 maxsize 大小对应 |
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 get %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["thread1", "thread2", "thread3", "thread4"]
nameList = ["1", "2", "3", "4", "5", "6","7","8"]
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")
运行结果:
Starting thread1
Starting thread2
Starting thread3
Starting thread4
thread4 get 1
thread2 get 2
thread1 get 3
thread3 get 4
thread4 get 5
thread3 get 6
thread1 get 7
thread2 get 8
Exiting thread4
Exiting thread3
Exiting thread2
Exiting thread1
Exiting Main Thread
以上就关于Python的多线程编程涉及的_thread,Threading多线程模块,多线程同步,队列做了简单总结,如果有不正确或者需要补充的地方,欢迎评论区留言,谢谢!