多线程深入理解和守护线程、子线程、锁、queue、evenet等介绍
1、多线程类的继承
import threading
import time
class MyThreading(threading.Thread):
def __init__(self,n):
super(MyThreading,self).__init__()
self.n = n
def run(self):
print("threading %s"%(self.n))
time.sleep(2) threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start() E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
threading 2
。。。。。。。
2、线程测试案例
import threading
import time
class MyThreading(threading.Thread):
def __init__(self,n):
super(MyThreading,self).__init__()
self.n = n
def run(self):
time.sleep(2)
print("threading %s"%(self.n)) threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start() print("main") E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
main
threading 2
3、多线程时间测试案例
import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(2) starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
t1.start()
list.append(t1) for i in list :
i.join() print("end") endtime = time.time()
print("cost:", endtime-starttime) E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
end
cost: 2.007871150970459 Process finished with exit code 0
4、守护线程概念,默认情况下为非守护线程,即主线程推出前,需要等待所有的非守护线程结束放可以推出。而守护线程就表示这个线程“不重要”,即主线程结束时候,无需等待守护线程是否执行完成。
import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(5)
print("setDaemon end ") starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
# t1.setDaemon(True)
t1.start()
list.append(t1) print("main end")
E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end Process finished with exit code 0 import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(5)
print("setDaemon end ") starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
t1.setDaemon(True)
t1.start()
list.append(t1) print("main end") E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main end Process finished with exit code 0
5、GIL 和线程锁。GIL就是一把全局排他锁。他的作用就是保证同一时刻只有一个线程可以执行代码,对多线程有较大影响。
import threading
import time
lock = threading.Lock()
list = [ ] res = 0
def run(i):
# 在Python3.5中已经优化,结果都是50.在python2.7如果不加锁可能有一场
lock.acquire()
global res
res = res + 1
lock.release() starttime = time.time()
for i in range(0,50):
t1 = threading.Thread(target=run,args=(i,))
t1.setDaemon(True)
t1.start()
list.append(t1) for i in list:
i.join() print(res)
6、当有多重锁时候,可以使用Rlock,使用递归锁可以避免出现死锁的情况
7、信号量简单实用。信号量就相当于多把锁
# Author : xiajinqi
import threading
import time semaphore = threading.BoundedSemaphore() def run(i):
semaphore.acquire()
print("阮娇。。。。")
time.sleep()
semaphore.release() for i in range(,):
tt = threading.Thread(target=run,args=(i,))
tt.start()
8、event 在线程间简单应用,车子等红灯
# Author : xiajinqi
import threading
import time event = threading.Event() # - 绿灯 -20红灯,大于二十从0开始
def lighter():
count =
while True : if count >= and count < :
event.clear()
print("当前红灯")
count = count +
elif count >= :
count =
else :
event.set()
print("当前绿灯")
count +=
time.sleep()
def run():
while True :
time.sleep()
if event.is_set() : #event.waite( 如果没有值,就会一直卡主等待
print("开始过十字路口")
else :
print("开始等车")
event.wait() t1 = threading.Thread(target=lighter)
t2 = threading.Thread(target=run) t1.start()
t2.start()
9、队列queue和列表、元组的区别。二者都有顺序。但是从列表取一个数据,数据还存在。而队列取出一个数据以后,改数据在队列就会被清空。符合实际应用场景。队列有三种:一、先进先去 二、先进后去 三、可以设置优先级别的队
import queue # 先进先去
qu= queue.Queue()
for i in range(1,5):
qu.put(i) while qu.qsize() >0:
print(qu.get()) # 先进后去
import queue # 先进先去
qu= queue.LifoQueue()
for i in range(1,5):
qu.put(i) while qu.qsize() >0:
print(qu.get()) E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/333.py
4
3
2
1 import queue # 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue() list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")] for lt in list:
qq.put(lt) while qq.qsize() >0:
print(qq.get()) import queue # 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue() list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")] for lt in list:
qq.put(lt) while qq.qsize() >0:
print(qq.get())
10、消费者生产者模型,解耦,相互不影响
import queue
import time
import threading
qu = queue.Queue(maxsize=) # 每次生产十个
def Producder():
while True:
for i in range(,):
print("生产了两个骨头")
qu.put("骨头 %s"%(i))
time.sleep() # 生产者消费者模型,多个人生产多个人消费。
def Consumer(name) :
while True:
print("%s 吃了一个骨头 %s"%(name,qu.get()))
time.sleep(0.5) #两个消费
c1 = threading.Thread(target=Consumer,args=("test1",))
c2 = threading.Thread(target=Consumer,args=("test2",))
pd1 = threading.Thread(target=Producder)
pd1.start()
c1.start()
c2.start()
多线程深入理解和守护线程、子线程、锁、queue、evenet等介绍的更多相关文章
- [Java][Android] 多线程同步-主线程等待全部子线程完毕案例
有时候我们会遇到这种问题:做一个大的事情能够被分解为做一系列相似的小的事情,而小的事情无非就是參数上有可能不同样而已! 此时,假设不使用线程,我们势必会浪费许多的时间来完毕整个大的事情.而使用线程的话 ...
- Unity3d 创建线程 子线程与主线程通信
创建子线程 一,不带参数 Thread resourcesLoadThread=new Thread (this.resourceLoadTxt); resourcesLoadThread.Sta ...
- NSThread 子线程 Cocoa NSOperation GCD(Grand Central Dispatch) 多线程
单词:thread 英 θred:n 线.思路.vt 穿过.vi 穿透过 一. 进程.线程 进程:正在进行中的程序被称为进程,负责程序运行的内存分配,每一个进程都有自己独立的虚拟内存空间 线程: ...
- Tasks遇到的一些坑,关于在子线程中对线程权限认证。
一般情况下,不应该在执行多线程认证的时候对其子线程进行身份认证,如:A线程的子线程B和子线程C. 当使用 Parallel.ForEach方法时,只有自身线程能够拥有相对应的权限,其子线程权限则为NU ...
- Android——子线程操作主线程
子线程不能直接操作主线程 UI线程 //水平进度条 public void jdt1_onclick(View view) { final ProgressDialog pd = new Progre ...
- C#子线程执行完后通知主线程
其实这个比较简单,子线程怎么通知主线程,就是让子线程做完了自己的事儿就去干主线程的转回去干主线程的事儿. 那么怎么让子线程去做主线程的事儿呢,我们只需要把主线程的方法传递给子线程就行了,那么传递方法就 ...
- C#子线程执行完后通知主线程(转)
其实这个比较简单,子线程怎么通知主线程,就是让子线程做完了自己的事儿就去干主线程的转回去干主线程的事儿. 那么怎么让子线程去做主线程的事儿呢,我们只需要把主线程的方法传递给子线程就行了,那么传递方法 ...
- 线程概念( 线程的特点,进程与线程的关系, 线程和python理论知识,线程的创建)
参考博客: https://www.cnblogs.com/xiao987334176/p/9041318.html 线程概念的引入背景 进程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运 ...
- python 全栈开发,Day41(线程概念,线程的特点,进程和线程的关系,线程和python 理论知识,线程的创建)
昨日内容回顾 队列 队列 : 先进先出.数据进程安全 队列实现方式: 管道 + 锁 生产者消费者模型 : 解决数据供需不平衡 管道 双向通信 数据进程不安全 EOFError: 管道是由操作系统进行引 ...
随机推荐
- java 分次读取大文件的三种方法
1. java 读取大文件的困难 java 读取文件的一般操作是将文件数据全部读取到内存中,然后再对数据进行操作.例如 Path path = Paths.get("file path&qu ...
- python之内置函数,匿名函数
什么是内置函数? 就是Python给你提供的,拿来直接用的函数,比如print,input等等.其实就是我们在创建.py的时候python解释器所自动生成的内置的函数,就好比我们之前所学的作用空间 内 ...
- 3D旋转相册的实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Asp.Net MVC源码调试
首先下载MVC源代码,下载地址为:https://aspnetwebstack.codeplex.com/ 打开项目,卸载test文件夹下的所有项目和System.Web.WebPages.Admin ...
- php性能调优
第一章 针对系统调用过多的优化 我这次的优化针对syscall调用过多的问题,所以使用strace跟踪apache进行分析. 1. apache2ctl -X & 使用-X(debug)参 ...
- [BZOJ 3441]乌鸦喝水
3441: 乌鸦喝水 Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 374 Solved: 148[Submit][Status][Discuss] ...
- Spotlight监控Linux服务器
1.安装 Spotlight on Unix 下载地址:http://worlddownloads.quest.com.edgesuite.net/Repository/www.quest.com/l ...
- CyclicBarrier和CountDownLatch笔记
一.CyclicBarrier的使用 Barrier是栅栏,障碍物的意思,这里将它理解为栅栏. Cyclic是重复利用的意思. CyclicBarrier:可重复利用的栅栏.这里附上官方文档的一句解释 ...
- visual stdio 安装OpenGL库文件
1.将下载的压缩包解开.将得到5个文件 1. 将glut解压出来,将当中的glut.h拷贝到C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC ...
- 随手练——S(n)=O(1),判断一个链表是否为“回文”
方法一:T(n)=O(n),S(n)=O(n) 走完一遍链表,每个值入栈,之后再走一遍链表,和每次弹出的栈顶进行比较. 核心: LNode *p = l->next; while (p) { s ...