python learning diary----thread, event, queue
进程与线程的区别:
线程==指令集,进程==资源集 (线程集)
1、同一个进程中的线程共享内存空间,进程与进程之间是独立的
2、同一个进程中的线程是可以直接通讯交流的,进程与间通讯必需通过一个中间的代理才能实现
3、创建线程简单,创建进程,是克隆父进程
4、一个线程可以控制和操作同一进程里的其他线程,但进程只能操作子进程
5、线程启动速度快,进程启动速度比较慢
线程示例:
1 import time ,threading 2 3 def run(attr): 4 print('输出:',attr) 5 time.sleep(3) 6 7 8 t1=threading.Thread(target=run,args=('第一个线程',)) 9 t2=threading.Thread(target=run,args=('第二个线程',))10 11 t1.start()#启动线程112 t2.start()#启动线程2
1 def run2(attr):2 print('输出:',attr)3 time.sleep(3)4 5 run2('第一个线程')6 run2('第二个线程')7 #以上转为串联执行
继承线程 类写线程
1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 5 import threading,time 6 7 class thre(threading.Thread):#继承线程中的类 8 def __init__(self,n,times): 9 super(thre,self).__init__()10 self.n=n11 self.teims=times12 def run(self):13 print('执行第一线程:',self.n)14 time.sleep(self.teims)15 16 star_time=time.time()17 t1=thre('第一线程',3)18 t2=thre('第二线程',4)19 t1.start()20 t2.start()21 t1.join()#join等待该线程执行完成22 23 t2.join()24 den_time=time.time()-star_time25 print(den_time)
等待线程执行完成,用.join


1 import time ,threading 2 lock=threading.Lock()#定义一个线程锁变量 3 def run(attr): 4 lock.acquire()#申请一个线程锁 5 global num 6 print('输出:',attr) 7 #time.sleep(3) 8 num+=1 9 lock.release()#释放线程锁10 time.sleep(3)11 print('输出完成'.center(10,'〓'))12 star_time=time.time()#开始时间13 14 num=015 re_lilst=[]#定义一个列表16 for i in range(50):17 t1=threading.Thread(target=run,args=(('第%s线程'%i),))#新建线程18 #t1.setDaemon(True)#设置为守护进程 当主线程完成,守护也停止19 t1.start()#起动线程20 re_lilst.append(t1)#不用JOIN,避免阻塞为串行21 22 print(threading.current_thread(),threading.active_count())#查看线程 的主 子 活跃线程23 #print('分线程'.center(40,'☆'))24 print('数字:',num)25 for i in re_lilst:#等待线程 完成26 i.join()27 print('数字:',num)28 print('主线程'.center(60,'◇'),threading.current_thread(),threading.active_count())29 30 den_time=time.time()-star_time#总共时间31 print(den_time)
守护进程,相当于主进程的下属,当主进程结束,无论守护进程内的是否执行完成,都会停止!


1 import time ,threading 2 lock=threading.Lock()#定义一个线程锁变量 3 def run(attr): 4 lock.acquire()#申请一个线程锁 5 global num 6 print('输出:',attr) 7 8 #time.sleep(3) 9 num+=110 lock.release()#释放线程锁11 time.sleep(3)12 print('输出完成'.center(10,'〓'))13 14 star_time=time.time()#开始时间15 16 num=017 re_lilst=[]#定义一个列表18 for i in range(50):19 t1=threading.Thread(target=run,args=(('第%s线程'%i),))#新建线程20 t1.setDaemon(True)#设置为守护进程 当主线程完成,守护也停止21 t1.start()#起动线程22 re_lilst.append(t1)#不用JOIN,避免阻塞为串行23 24 print(threading.current_thread(),threading.active_count())#查看线程 的主 子 活跃线程25 #print('分线程'.center(40,'☆'))26 print('数字:',num)27 # for i in re_lilst:#等待线程 完成28 # i.join()29 print('数字:',num)30 print('主线程'.center(60,'◇'),threading.current_thread(),threading.active_count())31 32 den_time=time.time()-star_time#总共时间33 print(den_time)
线程锁,在py3中可以不使用:
lock=threading.Lock()
lock.acquire()
递归锁 用于递归线程


1 import time ,threading 2 3 def run(i): 4 print('输出:-------',i) 5 lock.acquire()#申请锁 6 global num1 7 num1+=1 8 time.sleep(0.1) 9 lock.release()#释放锁10 return num111 12 def run2(i):13 lock.acquire()#申请锁14 global num215 print('输出:22',i)16 num2+=117 time.sleep(0.1)18 lock.release()#释放锁19 return num220 21 def run3(i):22 lock.acquire()#申请锁23 res=run(i)24 print('输出:333',i)25 res2=run2(i)26 time.sleep(0.1)27 print(res,res2)28 lock.release()#释放锁29 30 31 if __name__ == '__main__':32 star_time=time.time()#开始时间\33 num1,num2=0,034 #lock=threading.Lock()#定义一个线程锁,如是线程锁,递归时会出错35 lock=threading.RLock()#定义一个递归锁36 37 for i in range(10):38 #t1=threading.Thread(target=run,args=(('第%s线程'%i),))#新建线程39 t1=threading.Thread(target=run3,args=(('第%s线程'%i),))#新建线程40 t1.start()#起动线程41 42 else:43 print('活跃线程数:',threading.active_count())#查看线程 活跃线程数44 45 46 while threading.active_count()!=1:#不只一个线程,就是说,判断是否是剩下主线程47 #print(threading.active_count())#查看线程 活跃线程数48 pass49 else:50 print('主线程:pid,活跃线程数'.center(60,'◇'),threading.current_thread(),threading.active_count())#51 den_time=time.time()-star_time#总共时间52 print(den_time)53 print(num1,num2)
信号量 相当与 多个线程锁


1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 5 #!usr/bin/env python 6 #-*-coding:utf-8-*- 7 # Author calmyan 8 import time ,threading 9 10 def run(attr):11 semaphore.acquire()#申请信号量线程锁12 global num13 print('输出:',attr)14 time.sleep(1)15 semaphore.release()#释放信号量线程锁16 17 star_time=time.time()#开始时间18 if __name__ == '__main__':19 20 semaphore=threading.BoundedSemaphore(4)#信号量 最多允许几个线程同时运行(多把锁)21 for i in range(50):22 t1=threading.Thread(target=run,args=(('第%s线程'%i),))#新建线程23 t1.start()#起动线程24 25 while threading.active_count()!=1:#不只一个线程,就是说,判断是否是剩下主线程26 pass27 else:28 print('主线程'.center(60,'◇'),threading.current_thread(),threading.active_count())29 den_time=time.time()-star_time#总共时间30 print(den_time)
Event 线程标志
红绿灯示例


1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 5 import threading,time 6 7 event=threading.Event()#生成一个标示位对象 8 def lighter():# 9 count=0 #定义时间秒数10 event.set()#设置标志位11 while True:12 if count>9 and count<15:#设定为红灯13 event.clear()#清除标志位,14 print('\033[41;1m变为红灯!\033[0m')15 elif count>=15 and count<18 :#为黄灯16 17 print('\033[43;1m变为黄灯!\033[0m')18 elif count>=18:19 event.set()#设置标志位20 print('\033[42;1m变为绿灯!\033[0m')21 count=0#重新计时22 else:23 print('\033[42;1m绿灯中.....!\033[0m')24 time.sleep(1)25 count+=1#每一秒钟加一次26 27 28 def car(name):29 while True:30 if event.is_set():#如果有标志 说明为绿灯31 print('[%s]在行驶中....'%name)32 time.sleep(1)33 else:34 print('[%s]在等待中.....'%name)35 event.wait()#等待获取标志36 print('绿灯亮了,[%s]继续行驶...'%name)37 time.sleep(1)38 39 40 light=threading.Thread(target=lighter,)#定义一个线程41 light.start()#启动线程42 43 car1=threading.Thread(target=car,args=('红旗轿车',))#生成一个汽车线程44 car1.start()
队列 生产者消费者模型


1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 5 #队列 生产者消费者模型 6 7 import threading,time,queue 8 9 q=queue.Queue()#创建一个队列10 11 def produ(name):#生产函数12 count=013 while True:14 bz=name+str(count)15 q.put(bz)16 print('[%s]生产了,第[%s]个[%s]g 包子'%(name,count,bz))17 count+=118 time.sleep(1.5)19 20 def consump(name):#消费者21 while True:22 i=q.get()#取23 print('[%s]拿到包子[%s],并吃了'%(name,i))24 time.sleep(0.5)25 26 27 p1=threading.Thread(target=produ,args=('王五包子铺',))#创建一个新线程 生产者28 p2=threading.Thread(target=produ,args=('麻子六包子铺',))#创建一个新线程 生产者29 r1=threading.Thread(target=consump,args=('张三',))#创建一个新线程 消费者30 r2=threading.Thread(target=consump,args=('李四',))#创建一个新线程 消费者31 p1.start()32 p2.start()33 r1.start()34 r2.start()
The above is the detailed content of python learning diary----thread, event, queue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.
