Python 多线程threading学习
上一节学习了threading.Lock、threading.RLock、threading.Condition,如果全部理解的话,同步方面的知识应该不错的了。threading还有一个Event类,这个类也是用来同步的,不过这个类提供线程之间的模型也最为简单,了解即可。其实对于熟悉Condition的来说,Event就不是特别必要了。不过有时候线程的事情未必会需要Condition,能用个轻量级的Event解决就不必使用牛刀了。
Event的说明如下:
This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.
An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.
这个看说明就知道什么意思。只是把锁包装一下,添加wait方法。算是锁最近单的实现了。
唯一需要注意的是wait方法的解释:
wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
这个wait是个阻塞操作,这点使用时要注意。
#encoding=gbk
import threading
import time
class MyThread(threading.Thread):
def __init__(self, signal):
threading.Thread.__init__(self)
self.singal = signal
def run(self):
print "I am %s,I will sleep ..."%self.name
self.singal.wait()
print "I am %s, I awake..." %self.name
if __name__ == "__main__":
singal = threading.Event()
for t in range(0, 3):
thread = MyThread(singal)
thread.start()
print "main thread sleep 3 seconds... "
time.sleep(3)
singal.set()
后面还有一个Semaphore类,这个类的说明如下:
This is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used P() and V() instead of acquire() and release()).
A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release().
按照解释,semaphore管理一个内置的计数器,调用acquire方法是-1,调用release方法时+1,负责某个资源可以使用的线程数。实际上是控制在某个资源上,同时可以上几把锁,有几个线程来访问。semephore的构造方法能够选择选择内置计数器的初始值,默认初始值为1。
这个结合Condition和Event的思路就清楚了,实际上是在锁上添加了限制。
#encoding=gbk
import threading
import time
class semaphore_thread(threading.Thread):
def __init__(self,semaphore):
threading.Thread.__init__(self);
self.semaphore = semaphore
def run(self):
if semaphore.acquire():
print "%s get semaphore" %(threading.currentThread().getName())
time.sleep(3)
semaphore.release()
print "%s release semaphore" %(threading.currentThread().getName())
if __name__ == "__main__":
semaphore = threading.Semaphore(3)
for i in range(10):
t=semaphore_thread(semaphore)
t.start()
根据输出结果,可以看到在同一个时刻,最多只能有三个线程获得锁运行,其它线程都处于等待状态,实现资源的控制。
另外threading模块还有个BounderSemaphore,这个是个Factory
function,直接返回一个bounded semaphore,这个BoundedSemaphore能够确保当前值不会大于初始值,否则ValueError会被抛出来。其实这个BoundedSemaphore就是Semaphore添加边界检查的功能,不再举例了。
threading包到这里就告一段落了,回顾一下,我们学习了如下类:
threading.Thread
threading.Timer
threading.Lock
threading.RLock
threading.Condition
threading.Event
threading.Semaphore
threading.BoundedSemaphore
这些类的熟练使用能够保证你准确安全的使用并发多线程。
不过学习完多线程就Ok了?No,这些线程的使用实际上是单个Processor流转处理各个Thread,这个确实很快,至少我们感觉不出来。
不过对于多Processor的处理,使用线程模型只是利用了有限的Processor,同样Python提供了multiprocessing包来提升多核的处理能力。这个算是threading的进阶,有时间的话会分析下multiprocessing的处理过程。
分享到:
相关推荐
python多线程-threading模块.pdf
python多线程-threading模块.docx
1、多线程的理解 多进程和多线程都可以执行多个任务,线程是进程的一部分。...2、Python多线程创建 在Python中,同样可以实现多线程,有两个标准模块thread和threading,不过我们主要使用 更高级的threading模块。
python多线程threading.doc
threading模块API是面向对象的,其中最重要的是线程类Thread,此外还有很多线程相关函数,这些函数常用的有:返回当前处于活动状态的线程数。例如:#
python 08、多任务编程多线程 3-1_进程间通信、同步互斥、threading线程_Day03_AM.mp4
Python进程Process模块-Python零基础⼊门教程 Python进程Process模块-Python零基础⼊门教程 ⽬录 ⼀.... ⼆.Python 进程 Process 模块 ⼆.Python 进程 Process 模块 对于线程操作可以⽤ threading 模块,那么对于进程的
Python多线程编程文档说明 多进程编程 一、 multiprocessing 模块 1. multiprocessing 模块提供了多进程编程的能力 它的API非常类似于 threading 模块,但是也提供了一些threading 模块不具有的能力 相比于线程,它...
Python多线程编程方式2 threading库的介绍源码
threading模块和thread模块练习
python基础_31_Python_threading_1_什么是多线程_(教学教程tutorial)
Python多线程套接字编程全文共10页,当前为第1页。Python多线程套接字编程全文共10页,当前为第1页。Python多线程套接字编程 Python多线程套接字编程全文共10页,当前为第1页。 Python多线程套接字编程全文共10页,...
Python多线程爬虫 Python多线程模块 在Python中可使用的多线程模块主要有两个,thread和threading模块。 threading模块允许创建和管理线程,提供了更多的同步原语。threading模块中最常用的类是Thread。 Python多...
主要讲述Python多线程编程,主要讲述的thread库,threading库,Queue库等实现多线程编程
调用类中get_target()方法即可开始扫描,可在port_list.txt中自定义扫描端口,算是一个工具模块,调用方便,自定义线程类支持可调节线程数量,可根据自己需要调整,由于是相当于重构默认的threading模块,编写了一个...
现在这个例子添加了多线程 之前的例子有解释:https://blog.csdn.net/y363893017/article/details/105676878 大家可以自己去看,仅供学习,提供思路。 以下是我自己电脑上的截图 两个线程上传 上传完一个后 服务端...
python 多线程的同步机制 以python2例程的方式讲解了python 多线程的同步 常用的方法,主要是锁、条件同步、队列 多线程的同步 多线程情况下最常见的问题之一:数据共享; 当多个线程都要去修改某一个共享数据...
Python_threading_6_锁_lock_(多线程_教学教程tutorial)
本文实例为大家分享了python多线程实现TCP服务端的具体代码,供大家参考,具体内容如下 需求 1.创建一个TCP服务器接收服务端发送的信息并给予答复 2.以多线程方式实现接收客户端信息 3.间客户端发送的信息解码...
python多线程详解目录python多线程详解一、线程介绍什么是线程为什么要使用多线程二、线程实现 threading模块 自定义线程 守护线程 主线程等待子