search
HomeBackend DevelopmentPython Tutorialpython learning diary----thread, event, queue

python learning diary----thread, event, queue

Jun 23, 2017 am 11:05 AM
pythonone daythread

进程与线程的区别:

线程==指令集,进程==资源集  (线程集)

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)
View Code

守护进程,相当于主进程的下属,当主进程结束,无论守护进程内的是否执行完成,都会停止!

 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)
View Code

线程锁,在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)
View Code

信号量  相当与 多个线程锁 

 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)
View Code

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 and 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()
View Code

 

队列  生产者消费者模型

 

 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()
View Code

 

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software