python3 多线程编程
0.什么是线程
1. 多线程模块
2. 创建线程的方法
3. join()方法
4.isAlive()方法
5. name属性和daemon属性
6.线程的同步---锁
7.线程的同步---Event对象
8.线程的同步---Condition条件变量
1. 多线程模块
python3对多线程支持的是 threading 模块,应用这个模块可以创建多线程程序,并且在多线程间进行同步和通信。在python3 中,可以通过两种方法来创建线程:
第一:通过 threading.Thread 直接在线程中运行函数;第二:通过继承 threading.Thread 类来创建线程
view plain copy
- import threading
- def threadfun(x,y): #线程任务函数 threadfun()
- for i in range(x,y):
- print(i)
- ta = threading.Thread(target=threadfun,args=(1,6)) #创建一个线程ta,执行 threadfun()
- tb = threading.Thread(target=threadfun,args=(10,15)) #创建一个线程tb,执行threadfun()
- ta.start() #调用start(),运行线程
- tb.start() #调用start(),运行线程
- '''''打印:1 2 3 4 5 10 11 12 13 14'''
2.通过继承 thread.Thread 类 来创建线程
这种方法只需要重载 threading.Thread 类的 run 方法,然后调用 start()开启线程就可以了
- import threading
- class mythread(threading.Thread):
- def run(self):
- for i in range(1,5):
- print(i)
- ma = mythread();
- mb = mythread();
- ma.start()
- mb.start()
view plain copy
- import threading
- import time
- class mythread(threading.Thread):
- def run(self):
- self.i = 1
- print('%d'%(self.i))
- self.i = self.i+1
- time.sleep(1) #睡眠一秒
- print('%d'%(self.i))
- time.sleep(1)
- if __name__ == '__main__':
- ta = mythread() #实例化线程
- ta.start() #开启ta线程
- ta.join() #主线程等待 ta线程结束才继续执行
- print('main thread over')
view plain copy
- import threading
- import time
- class mythread(threading.Thread):
- def run(self):
- time.sleep(2)
- if __name__ == '__main__':
- ta = mythread() #实例化线程
- print(ta.isAlive()) #打印False,因为未执行 start()来使ta线程运行
- ta.start()
- print(ta.isAlive()) #打印Ture,因为ta线程运行了
- time.sleep(3)
- print(ta.isAlive()) #打印False,因为ta线程已经结束了
5. name属性和daemon属性
1.name属性表示线程的线程名 默认是 Thread-x x是序号,由1开始,第一个创建的线程名字就是 Thread-1
- import threading
- import time
- class mythread(threading.Thread):
- def run(self):
- pass
- if __name__ == '__main__':
- ta = mythread() #实例化线程
- ta.name = 'thread-ta'
- tb = mythread()
- tb.start()
- ta.start()
- print(ta.name) #打印 thread-ta
- print(tb.name) #打印 Thread-2
view plain copy
- import threading
- import time
- class mythread(threading.Thread):
- def run(self):
- time.sleep(2)
- print('my thread over')
- def main():
- ta = mythread()
- ta.daemon = True
- ta.start()
- print('main thread over')
- if __name__ == '__main__':
- main()
- #打印结果 :main thread over 然后马上结束程序
6.线程的同步---锁
当一个进程拥有多个线程之后,如果他们各做各的任务互没有关系还行,但既然属于同一个进程,他们之间总是具有一定关系的。比如多个线程都要对某个数据进行修改,则可能会出现不可预料的结果。为保证操作正确,就需要引入锁来进行线程间的同步。
python3 中的 threading 模块提供了
RLock锁(可重入锁)。对于某一时间只能让一个线程操作的语句放到 RLock的acquire 方法 和 release方法之间。即
acquire()方法相当于给RLock 锁 上锁,而 release() 相当于解锁。
- import threading
- import time
- class mythread(threading.Thread):
- def run(self):
- global x #声明一个全局变量
- lock.acquire() #上锁,acquire()和release()之间的语句一次只能有一个线程进入,其余线程在acquire()处等待
- x += 10
- print('%s:%d'%(self.name,x))
- lock.release() #解锁
- x = 0
- lock = threading.RLock() #创建 可重入锁
- def main():
- l = []
- for i in range(5):
- l.append(mythread()) #创建 5 个线程,并把他们放到一个列表中
- for i in l:
- i.start() #开启列表中的所有线程
- if __name__ =='__main__':
- main()
打印结果:
Thread-1:10
Thread-2:20
Thread-3:30
Thread-4:40
Thread-5:50
7.线程的同步---Event对象
Event对象存在于 threading 模块中。Event 实例管理着 一个内部标志,通过 set() 方法来将该标志设置成 True,使用
clear() 方法将该标志重置成 False
wait() 方法会使当前线程阻塞直到标志被设置成 True,wait()可以选择给他一个参数,代表时间,代表阻塞多长时间,若不设置就是阻塞直到标志被设置为True
isSet()方法 :能判断标志位是否被设置为True
- import threading
- import time
- class Mon(threading.Thread):
- def run(self):
- Dinner.clear()
- print('Cooking dinner')
- time.sleep(3)
- Dinner.set() #标志设置为True
- print(self.name,':dinner is OK!')
- class Son(threading.Thread):
- def run(self):
- while True:
- if Dinner.isSet(): #判断标志位是否被设置为True
- break
- else:
- print('dinner isnot ready!')
- Dinner.wait(1)
- print(self.name,':Eating Dinner')
- def main():
- mon = Mon()
- son = Son()
- mon.name = 'Mon'
- son.name = 'Son'
- mon.start()
- son.start()
- if __name__ == '__main__':
- Dinner = threading.Event()
- main()
- '''''
- Cooking dinner
- dinner isnot ready!
- dinner isnot ready!
- dinner isnot ready!
- Mon :dinner is OK!
- Son :Eating Dinner
- '''
注意,这里的wait()跟上面Event提到的wait()不是同一样东西
notify()
发出资源可用的信号,唤醒任意一条因 wait()阻塞的进程
notifyAll()
发出资源可用信号,唤醒所有因wait()阻塞的进程
下面给出一个例子,一家蛋糕店:只会做一个蛋糕,卖出后才会再做一个。绝对不会做积累到2个蛋糕。
- import threading
- import time
- class Server(threading.Thread):
- def run(self):
- global x
- while True:
- con.acquire()
- while x>0:
- con.wait()
- x += 1
- time.sleep(1)
- print(self.name,':I make %d cake!'%(x))
- con.notifyAll()
- con.release()
- class Client(threading.Thread):
- def run(self):
- global x
- con.acquire()
- while x == 0:
- con.wait()
- x-=1
- print(self.name,'I bought a cake! the rest is %d cake'%(x))
- con.notifyAll()
- con.release()
- def main():
- ser = Server()
- ser.name = 'Cake Server'
- client = []
- for i in range(3):
- client.append(Client())
- ser.start()
- for c in client:
- c.start()
- if __name__ =='__main__':
- x = 0
- con = threading.Condition()
- main()
- '''''
- 打印结果:
- Cake Server :I make 1 cake!
- Thread-3 I bought a cake! the rest is 0 cake
- Cake Server :I make 1 cake!
- Thread-4 I bought a cake! the rest is 0 cake
- Cake Server :I make 1 cake!
- Thread-2 I bought a cake! the rest is 0 cake
- Cake Server :I make 1 cake!
- '''
python3 多线程编程的更多相关文章
- Python3 多线程编程 - 学习笔记
线程 什么是线程 特点 线程与进程的关系 Python3中的多线程 全局解释器锁(GIL) GIL是啥? GIL对Python程序有啥影响? 改善GIL产生的问题 Python3关于多线程的模块 多线 ...
- Python3 多线程编程(thread、threading模块)
threading是对thread的封装. 1.开启线程: t=threading.Thread(target=sayhi,args=('hh',)) t.start() 或者先建一个Thread的继 ...
- Python3 多线程编程 threading模块
性能自动化测试除了用jmeter还可以用python threading模块做 一.threading模块定义 Python 2.4中包含的较新的线程模块为线程提供了更强大的高级支持. 线程模块公开线 ...
- python --- 基础多线程编程
在python中进行多线程编程之前必须了解的问题: 1. 什么是线程? 答:线程是程序中一个单一的顺序控制流程.进程内一个相对独立的.可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程 ...
- Python中的多线程编程,线程安全与锁(二)
在我的上篇博文Python中的多线程编程,线程安全与锁(一)中,我们熟悉了多线程编程与线程安全相关重要概念, Threading.Lock实现互斥锁的简单示例,两种死锁(迭代死锁和互相等待死锁)情况及 ...
- Python中的多线程编程,线程安全与锁(一)
1. 多线程编程与线程安全相关重要概念 在我的上篇博文 聊聊Python中的GIL 中,我们熟悉了几个特别重要的概念:GIL,线程,进程, 线程安全,原子操作. 以下是简单回顾,详细介绍请直接看聊聊P ...
- Python3 多进程编程 - 学习笔记
Python3 多进程编程(Multiprocess programming) 为什么使用多进程 具体用法 Python多线程的通信 进程对列Queue 生产者消费者问题 JoinableQueue ...
- Web Worker javascript多线程编程(一)
什么是Web Worker? web worker 是运行在后台的 JavaScript,不占用浏览器自身线程,独立于其他脚本,可以提高应用的总体性能,并且提升用户体验. 一般来说Javascript ...
- Web Worker javascript多线程编程(二)
Web Worker javascript多线程编程(一)中提到有两种Web Worker:专用线程dedicated web worker,以及共享线程shared web worker.不过主要讲 ...
随机推荐
- python 属性 property、getattr()、setattr()详解
直奔主题 使用中文注释需要使用 #-*-coding:utf-8-*- property property在python中有2中使用property方法:1.@property @属性名称.sette ...
- ajax请求后台返回map类型并如何展示
前台jsp或者ftl文件接收返回结果: <input type="hidden" name="selectedModelListStr" id=" ...
- iOS多线程(转)
关于iOS多线程,你看我就够了 字数8596 阅读28558 评论74 喜欢313 在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项.当然也会给出几种多线程的案例 ...
- UVA 679 Dropping Balls 由小见大,分析思考 二叉树放小球,开关翻转,小球最终落下叶子编号。
A number of K balls are dropped one by one from the root of a fully binary tree structure FBT. Each ...
- Power Network - poj 1459 (最大流 Edmonds-Karp算法)
Time Limit: 2000MS Memory Limit: 32768K Total Submissions: 24788 Accepted: 12922 Description A ...
- apache2+svn Cannot load modules/mod_dav_svn.so into server: \xd5\xd2\xb2\xbb\xb5\xbd\xd6\xb8\xb6\xa8\xb5\xc4\xc4\xa3\xbf\xe9\xa1\xa3
按照svn里的readme文件安装配置apache2与svn后, 启动apache2服务的时候 出现下面的问题 Cannot load C:/Program Files/Apache Software ...
- 移动web开发经验总结(转)
1.<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-sca ...
- knockout Ajax异步无刷新分页 Demo +mvc+bootstrap
最近工作中web客户端需要用到knockout,在此记录下一些Demo,以后用到的时候查找起来方便.也希望给新入门的knockout使用者一点经验.knockout官方文档.这儿是一个使用knocko ...
- 2204 Problem A(水)
问题 A: [高精度]被限制的加法 时间限制: 1 Sec 内存限制: 16 MB 提交: 54 解决: 29 [提交][状态][讨论版] 题目描述 据关押修罗王和邪狼监狱的典狱长吹嘘,该监狱自一 ...
- Laravel 的中大型专案架构
好文:http://oomusou.io/laravel/laravel-architecture/