线程的语法 (event,重要)

Python threading模块

2种调用方式

直接调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import threading
import time
def sayhi(num): #定义每个线程要运行的函数
    print("running on number:%s" %num)
    time.sleep(3)
if __name__ == '__main__':
    t1 = threading.Thread(target=sayhi,args=(1,)) #生成一个线程实例
    t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一个线程实例
    t1.start() #启动线程
    t2.start() #启动另一个线程
    print(t1.getName()) #获取线程名
    print(t2.getName())

继承式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading
import time
class MyThread(threading.Thread):
    def __init__(self,num):
        threading.Thread.__init__(self)
        self.num = num
    def run(self):#定义每个线程要运行的函数
        print("running on number:%s" %self.num)
        time.sleep(3)
if __name__ == '__main__':
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()

 第二种有点傻

基本语法

is_alive() 当前活跃的线程

例子:

car1 = threading.Thread(target=car,args=('bmw',))
car1.start()
print(car1.is_alive())
if car1.is_alive():print('33')
if not car1.is_alive():print('444')

执行结果:

bmw wait red light
True
33

例子对比:

car1 = threading.Thread(target=car,args=('bmw',))
# car1.start()   注释掉
print(car1.is_alive()) 
if car1.is_alive():print('33')
if not car1.is_alive():print('444')

执行结果:

False
444

 

Join ()

等待!其实就wait()。

等待该线程执行完毕

Daemon()

守护进程!有句话怎么说来着!守护进程被吞噬!

# _*_coding:utf-8_*_
import time
import threadingstart_time=time.time()
def run(n):print('[%s]------running----\n' % n)time.sleep(2)print('--done--%s'%n)def run2(n):print('[%s]------running----\n' % n)time.sleep(5)print('--done--%s'%n)
lis_1=[]
t1 = threading.Thread(target=run, args=('run%1',))
t2 = threading.Thread(target=run2, args=('run%2',))lis_1.append(t1)
lis_1.append(t2)
# t2.setDaemon(True)# 将main线程设置为Daemon线程,它做为程序主线程的守护线程,当主线程退出时,m线程也会退出,由m启动的其它子线程会同时退出,不管是否执行完任务
t1.start()
t2.start()
#  看下就懂了,不懂试一试就想起来了
t1.join()
t2.join()print("---end time----",time.time()-start_time)

 

线程锁(互斥锁Mutex)

lock()

为什么上锁?因为好多线程同时修改一个数据,有先后顺序,有的没干完,就被gil了,所以对修改数据的地方加把锁,保证该数据的正确性!

lock = threading.Lock() #生成全局锁

不带锁例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import time
import threading
def addNum():
    global num #在每个线程中都获取这个全局变量
    print('--get num:',num )
    time.sleep(1)
    num  -=1 #对此公共变量进行-1操作
num = 100  #设定一个共享变量
thread_list = []
for in range(100):
    = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)
for in thread_list: #等待所有线程执行完毕
    t.join()
print('final num:', num )

 

带锁例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import time
import threading
def addNum():
    global num #在每个线程中都获取这个全局变量
    print('--get num:',num )
    time.sleep(1)
    lock.acquire() #修改数据前加锁
    num  -=1 #对此公共变量进行-1操作
    lock.release() #修改后释放
num = 100  #设定一个共享变量
thread_list = []
lock = threading.Lock() #生成全局锁
for in range(100):
    = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)
for in thread_list: #等待所有线程执行完毕
    t.join()
print('final num:', num )

RLock(递归锁)

这个主要针对函数甲里边包涵函数乙,函数乙又有函数丙

绕进去了,很麻烦,用lock的话容易死循环,所以用Rlock,一键上锁,保证不乱。例子看看就好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import threading,time
def run1():
    print("grab the first part data")
    lock.acquire()
    global num
    num +=1
    lock.release()
    return num
def run2():
    print("grab the second part data")
    lock.acquire()
    global  num2
    num2+=1
    lock.release()
    return num2
def run3():
    lock.acquire()
    res = run1()
    print('--------between run1 and run2-----')
    res2 = run2()
    lock.release()
    print(res,res2)
if __name__ == '__main__':
    num,num2 = 0,0
    lock = threading.RLock()
    for in range(10):
        = threading.Thread(target=run3)
        t.start()
while threading.active_count() != 1:
    print(threading.active_count())
else:
    print('----all threads done---')
    print(num,num2)

Semaphore(信号量)

互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading,time
def run(n):
    semaphore.acquire()
    time.sleep(1)
    print("run the thread: %s\n" %n)
    semaphore.release()
if __name__ == '__main__':
    num= 0
    semaphore  = threading.BoundedSemaphore(5#最多允许5个线程同时运行
    for in range(20):
        = threading.Thread(target=run,args=(i,))
        t.start()
while threading.active_count() != 1:
    pass #print threading.active_count()
else:
    print('----all threads done---')
    print(num)

 

Events  

重点,标识符,event可以理解成对全局变量不停的修改,!!!!!!这个我感觉后边能用的到,用event来验证result

语法有

event = threading.Event()

创建标识符

 

event.set( )

设置标识符

 

event.wait( )

等待标识符出现,一旦出现立刻执行后边的代码

print(‘杀啊!!’)
event.wait()
print( ‘撤退!!,杀个瘠薄’

 

event.clear( )

清空标志位

通过Event来实现两个或多个线程间的交互

红绿灯例子!!

import time
import threadingevent=threading.Event()def car(name):while True:if event.is_set():print('%s is runing'%name)time.sleep(1)else:print('%s wait red light' % name)event.wait()time.sleep(1)def light():conent = 0event.set()while True:if conent >5 and conent <10:event.clear()print('\033[41;1mred light is on ....\033[0m')elif conent >10:event.set()conent = 0else:print('\033[42;1mgreen is come!\033[0m')time.sleep(1)conent += 1light = threading.Thread(target=light,)car2 = threading.Thread(target=car,args=('tesla',))car1 = threading.Thread(target=car,args=('bmw',))
light.start()
car1.start()
car2.start()

运行结果

 

转载于:https://www.cnblogs.com/PYlog/p/9240692.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280005.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

求最大值和下标值

本题要求编写程序&#xff0c;找出给定的n个数中的最大值及其对应的最小下标&#xff08;下标从0开始&#xff09;。 输入格式: 输入在第一行中给出一个正整数n&#xff08;1<n≤10&#xff09;。第二行输入n个整数&#xff0c;用空格分开。 输出格式: 在一行中输出最大值及…

windows应用商店修复_如何修复Windows应用商店中的卡死下载

windows应用商店修复Though it’s had its share of flaky behavior since being introduced in Windows 8, the Windows Store has gotten more reliable over time. It still has the occasional problems, though. One of the more irritating issues is when an app update…

OpenWrt:Linux下生成banner

Linux下有三个小工具可以生成banner&#xff1a;1、banner使用#生成banner&#xff1b;2、figlet使用一些普通字符生成banner&#xff1b;3、toilet使用一些复杂的彩色特殊字符生成banner。使用apt-get安装的时候需要输入以下命令&#xff1a; $ sudo apt-get install sysvbann…

新冠病毒中招 | 第二天

今天跟大家分享我个人感染奥密克戎毒株第二天的经历和感受。早上7点多自然醒来&#xff0c;已经没有四肢乏力的感觉&#xff0c;但是身体的本能还是告诉我不愿意动弹。由于第一天躺着睡了一天&#xff0c;确实是躺得腰酸背疼的。起床量了一下体温36.4正常&#xff0c;决定今天不…

输出到Excel

HSSFWorkbook oBook new HSSFWorkbook(); NPOI.SS.UserModel.ISheet oSheet oBook.CreateSheet(); #region 输出到Excel MemoryStream ms new MemoryStream(); oBook.Write(ms);string sExportPath ""; using (SaveFileDialog saveFileDialog1 new SaveFileDial…

JavaScript 精粹 基础 进阶(5)数组

转载请注明出处 原文连接 blog.huanghanlian.com/article/5b6… 数组是值的有序集合。每个值叫做元素&#xff0c;每个元素在数组中都有数字位置编号&#xff0c;也就是索引。JS中的数组是弱类型的&#xff0c;数组中可以含有不同类型的元素。数组元素甚至可以是对象或其它数组…

icloud 购买存储空间_如何释放iCloud存储空间

icloud 购买存储空间Apple offers 5 GB of free iCloud space to everyone, but you’ll run up against that storage limit sooner than you’d think. Device backups, photos, documents, iCloud email, and other bits of data all share that space. Apple为每个人提供5 …

基于LAMP实现web日志管理查看

前言&#xff1a;日志是一个重要的信息库&#xff0c;如何高效便捷的查看系统中的日志信息&#xff0c;是系统管理员管理系统的必备的技术。实现方式&#xff1a;1、将日志存储于数据库。2、采用LAMP架构&#xff0c;搭建PHP应用&#xff0c;通过web服务访问数据库&#xff0c;…

WPF效果第二百零七篇之EditableSlider

前面简单玩耍一下快速黑白灰效果; 今天又玩了一下ZoomBlurEffect,来看看最终实现的效果:1、ps和cs文件都在Shazzam中,咱们自己随意玩耍;今天主角是下面这位:2、来看看自定义控件布局(TextBox、Slider、ToggleButton)&#xff1a;3、点击编辑按钮,我就直接偷懒了:private void E…

闲话高并发的那些神话,看京东架构师如何把它拉下神坛

转载:闲话高并发的那些神话&#xff0c;看京东架构师如何把它拉下神坛 高并发也算是这几年的热门词汇了&#xff0c;尤其在互联网圈&#xff0c;开口不聊个高并发问题&#xff0c;都不好意思出门。高并发有那么邪乎吗&#xff1f;动不动就千万并发、亿级流量&#xff0c;听上去…

c# Clone方法

clone是深拷贝&#xff0c;copy是浅拷贝&#xff0c;如果是值类型的话是没什么区别的&#xff0c;如果是引用类型的话深拷贝拷贝的事整个对象的数据&#xff0c;而浅拷贝仅仅拷贝对象的引用。因为类的实例是引用类型&#xff0c;要想用原有的类中的实例的数据的话&#xff0c;既…

使用MyQ打开车库门时如何接收警报

Chamberlain’s MyQ technology is great for opening and closing your garage door remotely with your smartphone, but you can also receive alerts whenever your garage door opens and closes (as well as receive alerts when it’s been open for an extended amount…

踏实工作,实现价值

工作&#xff0c;为实现自我价值 若想在漫长的职场生涯中稳步高升&#xff0c;首先要踏踏实实&#xff0c;专心致志、充满激情的去完成工作中的每一项任务&#xff0c;无论工作是繁重的还是琐碎的&#xff0c;都要严格要求自己全身心的去完成。而不是一味的抱怨&#xff0c;一味…

mac 防火墙禁止程序联网_如何允许应用程序通过Mac的防火墙进行通信

mac 防火墙禁止程序联网If you use a Mac, chances are you might not even realize that OS X comes with a firewall. This firewall helps ensure unauthorized app and services can’t contact your computer, and prevents intruders from sniffing out your Mac on a ne…

WPF-22 基于MVVM员工管理-02

我们接着上一节&#xff0c;这节我们实现crud操作&#xff0c;我们在EmployeeViewMode类中新增如下成员&#xff0c;并在构造函数中初始化该成员code snippetpublic EmployeeViewMode() {employeeService new EmployeeService();BindData();Employee new Employee();AddComma…

linux 3

-- Linux -- 开心的一天 vi   所有的 unix like 系统都会内置 vi 文本编辑器 vim  较多使用的,可以主动的以字体颜色辨别语法的正确性&#xff0c;方便程序设计 vi/vim 的使用 -- 命令模式&#xff08;Command mode&#xff09; 输入模式&#xff08;Insert mode&#x…

从零开始搭建一个简单的ui自动化测试框架02(pytest+selenium+allure)

二、先搭一个架子 在我还是小白连py语法都不太熟悉的时候&#xff0c;经常在网上看关于自学ui自动化测试的博客&#xff0c;最熟悉的套路莫过于先给你介绍一下selenium的各个api&#xff0c;然后写一套代码去登陆微博或者百度什么的&#xff0c;但我今天不愿意这么写&#xff0…

DML语言DDL

DML&#xff08;data manipulation language&#xff09;&#xff1a; 它们是SELECT、UPDATE、INSERT、DELETE&#xff0c;就象它的名字一样&#xff0c;这4条命令是用来对数据库里的数据进行操作的语言 。 DDL&#xff08;data definition language&#xff09;&#xff1a; D…

什么是Adobe Lightroom,我需要它吗?

Adobe Photoshop Lightroom confuses a lot of new photographers. It has Photoshop in the name, but it isn’t Photoshop? What gives? Adobe Photoshop Lightroom使许多新摄影师感到困惑。 它的名称是Photoshop&#xff0c;但不是Photoshop吗&#xff1f; 是什么赋予了&…

jquery中的serializeArray方法的使用

转载于:https://blog.51cto.com/11871779/2359556