[Python]
来源:互联网 发布:网络小贷与p2p的区别 编辑:程序博客网 时间:2024/06/05 20:24
文章从简书转入,只因它已不再是以前的简书
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 2017Thread-2: Tue Nov 28 17:26:48 2017Thread-1: Tue Nov 28 17:26:48 2017Thread-1: Tue Nov 28 17:26:50 2017Thread-2: Tue Nov 28 17:26:52 2017Thread-1: Tue Nov 28 17:26:52 2017Thread-1: Tue Nov 28 17:26:54 2017Thread-2: Tue Nov 28 17:26:56 2017Thread-2: Tue Nov 28 17:27:00 2017Thread-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 threadingimport time# 终止符exitFlag = 0class 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-2Thread-1: Tue Nov 28 17:33:22 2017Thread-1: Tue Nov 28 17:33:23 2017Thread-2: Tue Nov 28 17:33:23 2017Thread-1: Tue Nov 28 17:33:24 2017Thread-1: Tue Nov 28 17:33:25 2017Thread-2: Tue Nov 28 17:33:25 2017Thread-1: Tue Nov 28 17:33:26 2017退出线程:Thread-1Thread-2: Tue Nov 28 17:33:27 2017Thread-2: Tue Nov 28 17:33:29 2017Thread-2: Tue Nov 28 17:33:31 2017退出线程:Thread-2退出主线程
总结:执行 start() 方法开启线程;执行 exit()方法退出线程;执行 join() 加入线程池,等待其完成后,执行后续操作。
线程同步
如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步
线程锁(互斥锁Mutex)
使用 Thread
对象的 Lock
和 Rlock
可以实现简单的线程同步,这两个对象都有 acquire
方法和 release
方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire
和 release
方法之间。
不使用线程同步(不加锁)
示例:
import time, threading# 假定这是你的银行存款:balance = 0def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - ndef 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 - ndef 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,timedef 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: 4run the thread: 2run the thread: 3run the thread: 0run the thread: 1run the thread: 5run the thread: 9run the thread: 8run the thread: 6run the thread: 7run the thread: 11run the thread: 13run the thread: 10run the thread: 12run the thread: 14run the thread: 15run the thread: 19run the thread: 17run the thread: 18run the thread: 16----all threads done---0
总结:每次开启五个线程,顺序随机
PS: BoundedSemaphore() 改成 1,就变成了单线程,顺序执行
Timer
让一个方法在子线程里延迟执行,time.sleep() 是在主线程睡眠
代码示例:
import threadingdef 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 queueimport threadingimport timeexitFlag = 0class 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-3Thread-1 processing OneThread-2 processing TwoThread-3 processing ThreeThread-1 processing FourThread-2 processing Five退出线程:Thread-3退出线程:Thread-2退出线程:Thread-1退出主线程
总结:使用队列后, 线程是先进后出,即:LIFO
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- Python
- Centos下“ssh免密码登录不生效”问题
- HR4985是一种便于使用的内部集成了译码器的微步进电机驱动器
- git + zsh
- block,inline和inlinke-block细节对比及导航案例
- JavaScript中的语句结束符';'
- [Python]
- 二分查找(递归实现)
- 10. Regular Expression Matching
- vi /etc/redhat-release
- (洛谷 1164)小A点菜
- 为什么要有深度学习?系统学习清单
- AngularJS操作表格的增删改查
- PS小记
- <script language="javascript" type="text/javascript">