Table of Contents
1. Import thread module: " >1. Import thread module:
" >##2. Thread usage
3.1 使用Thread方法来创建:" >3.1 使用Thread方法来创建:
3.2.1 单线程" >3.2.1 单线程
3.2.2 多线程
" >3.2.2 多线程
3.2 重写线程的类方法" >3.2 重写线程的类方法
4.线程锁" >4.线程锁
4.1 Lock" >4.1 Lock
4.2 RLock" >4.2 RLock
4.3 条件锁" >4.3 条件锁
5.信号量" >5.信号量
5.1 有界信号量" >5.1 有界信号量
5.2 无界信号量" >5.2 无界信号量
6.Event" >6.Event
7.local" >7.local
8.Timer" >8.Timer
总结" >总结
Home Backend Development Python Tutorial An article will give you a comprehensive analysis of different threads

An article will give you a comprehensive analysis of different threads

Aug 10, 2023 pm 04:13 PM
python


#Preface

Before going through today’s knowledge points, do you know about threads, processes and coroutines? Let’s first have a preliminary understanding.


Thread

The scheduling unit of the central processor is simply the terminal execution in the program. The latter is equivalent to the position of younger brother.

Some people say that threads in python are useless. This is because of the GIL, but it is not blindly useless. After all, it is quite useful when performing io operations, and it is only used to perform calculations. It seems unsatisfactory. Let’s take a look at the specific usage of threads:

1. Import thread module:

import threading as t
Copy after login

##2. Thread usage

tt=t.Thread(group=None,target=None,name=None,args=(),kwargs={},name='',daemon=None)
group:线程组,必须是None
target:运行的函数
args:传入函数的参数元组
kwargs:传入函数的参数字典
name:线程名
daemon:线程是否随主线程退出而退出(守护线程)


Thread方法的返回值还有以下方法:
tt.start() : 激活线程,
tt.getName() : 获取线程的名称
tt.setName() :设置线程的名称 
tt.name : 获取或设置线程的名称
tt.is_alive() :判断线程是否为激活状态
tt.isAlive() :判断线程是否为激活状态
tt.setDaemon() 设置为守护线程(默认:False)
tt.isDaemon() :判断是否为守护线程
tt.ident :获取线程的标识符。只有在调用了start()方法之后该属性才有效
tt.join() :逐个执行每个线程,执行完毕后继续往下执行
tt.run() :自动执行线程对象


t的方法也有:
t.active_count(): 返回正在运行线程的数量
t.enumerate(): 返回正在运行线程的列表
t.current_thread().getName() 获取当前线程的名字
t.TIMEOUT_MAX 设置t的全局超时时间
Copy after login

Let’s take a look:

An article will give you a comprehensive analysis of different threads


##3. Create threads

Threads can be created using the Thread method, or they can be implemented by overriding the run method of the thread class. Threads can be divided into single threads and multi-threads.

3.1 使用Thread方法来创建:

3.1.1 单线程
def xc():
    for y in range(100):
        print('运行中'+str(y))
tt=t.Thread(target=xc,args=()) #方法加入到线程
tt.start()  #开始线程
tt.join() #等待子线程结束
Copy after login
3.1.2 多线程
def xc(num):
    print('运行:'+str(num))
c=[]
for y in range(100):
    tt=t.Thread(target=xc,args=(y,))
    tt.start() #开始线程
    c.append(tt) #创建列表并添加线程
for x in c:
    x.join()  #等待子线程结束
Copy after login

3.2 重写线程的类方法

3.2.1 单线程
class Xc(t.Thread): #继承Thread类
    def __init__(self):
        super(Xc, self).__init__() 
    def run(self):  #重写run方法
        for y in range(100):
            print('运行中'+str(y))
x=Xc() 
x.start() #开始线程
x.join()  #等待子线程结束


也可以这么写:
Xc().run() 和上面的效果是一样的
Copy after login
3.2.2 多线程
class Xc(t.Thread): #继承Thread类
    def __init__(self):
        super(Xc, self).__init__() 
    def run(self,num):  #重写run方法
        print('运行:'+str(num))
x=Xc()
for y in range(10):
    x.run(y) #运行
Copy after login

4.线程锁

为什么要加锁,看了这个你就知道了:

An article will give you a comprehensive analysis of different threads

多线程在运行时同时访问一个对象会产生抢占资源的情况,所以我们必须得束缚它,所以就要给他加一把锁把他锁住,这就是同步锁。要了解锁,我们得先创建锁,线程中有两种锁:Lock和RLock。

4.1 Lock

使用方法:

# 获取锁
当获取不到锁时,默认进入阻塞状态,设置超时时间,直到获取到锁,后才继续。非阻塞时,timeout禁止设置。如果超时依旧未获取到锁,返回False。
Lock.acquire(blocking=True,timeout=1)   


#释放锁,已上锁的锁,会被设置为unlocked。如果未上锁调用,会抛出RuntimeError异常。
Lock.release()
Copy after login

互斥锁,同步数据,解决多线程的安全问题:

n=10
lock=t.Lock()
def xc(num):
    lock.acquire()
    print('运行+:'+str(num+n))
    print('运行-:'+str(num-n))
    lock.release()
c=[]
for y in range(10):
    tt=t.Thread(target=xc,args=(y,))
    tt.start()
    c.append(tt)
for x in c:
    x.join()
Copy after login

这样就显得有条理了,而且输出也是先+后-。Lock在一个线程中多次使用同一资源会造成死锁。

死锁问题:

n=10
lock1=t.Lock()
lock2=t.Lock()
def xc(num):
  lock1.acquire()
  print('运行+:'+str(num+n))
  lock2.acquire()
  print('运行-:'+str(num-n))
  lock2.release()
  lock1.release()
c=[]
for y in range(10):
  tt=t.Thread(target=xc,args=(y,))
  tt.start()
  c.append(tt)
for x in c:
  x.join()
Copy after login


4.2 RLock

相比Lock它可以递归,支持在同一线程中多次请求同一资源,并允许在同一线程中被多次锁定,但是acquire和release必须成对出现。

使用递归锁来解决死锁:

n=10
lock1=t.RLock()
lock2=t.RLock()
def xc(num):
  lock1.acquire()
  print('运行+:'+str(num+n))
  lock2.acquire()
  print('运行-:'+str(num-n))
  lock2.release()
  lock1.release()
c=[]
for y in range(10):
  tt=t.Thread(target=xc,args=(y,))
  tt.start()
  c.append(tt)
for x in c:
  x.join()
Copy after login

这时候,输出变量就变得仅仅有条了,不在随意抢占资源。关于线程锁,还可以使用with更加方便:

#with上下文管理,锁对象支持上下文管理
with lock:   #with表示自动打开自动释放锁
  for i in range(10): #锁定期间,其他人不可以干活
    print(i)
  #上面的和下面的是等价的
if lock.acquire(1):#锁住成功继续干活,没有锁住成功就一直等待,1代表独占
  for i in range(10): #锁定期间,其他线程不可以干活
    print(i)
  lock.release() #释放锁
Copy after login


4.3 条件锁

等待通过,Condition(lock=None),可以传入lock或者Rlock,默认Rlock,使用方法:

Condition.acquire(*args)      获取锁


Condition.wait(timeout=None)  等待通知,timeout设置超时时间


Condition.notify(num)唤醒至多指定数目个数的等待的线程,没有等待的线程就没有任何操作


Condition.notify_all()  唤醒所有等待的线程 或者notifyAll()
Copy after login
def ww(c):
  with c:
    print('init')
    c.wait(timeout=5) #设置等待超时时间5
    print('end')
def xx(c):
  with c:
    print('nono')
    c.notifyAll() #唤醒所有线程
    print('start')
    c.notify(1) #唤醒一个线程
    print('21')
c=t.Condition() #创建条件
t.Thread(target=ww,args=(c,)).start()
t.Thread(target=xx,args=(c,)).start()
Copy after login

这样就可以在等待的时候唤醒函数里唤醒其他函数里所存在的其他线程了。


5.信号量

信号量可以分为有界信号量和无解信号量,下面我们来具体看看他们的用法:

5.1 有界信号量

它不允许使用release超出初始值的范围,否则,抛出ValueError异常。

#构造方法。value为初始信号量。value小于0,抛出ValueError异常
b=t.BoundedSemaphore(value=1)  


#获取信号量时,计数器减1,即_value的值减少1。如果_value的值为0会变成阻塞状态。获取成功返回True
BoundedSemaphore.acquire(blocking=True,timeout=None)  


#释放信号量,计数器加1。即_value的值加1,超过初始化值会抛出异常ValueError。
BoundedSemaphore.release()  


#信号量,当前信号量
BoundedSemaphore._value
Copy after login

An article will give you a comprehensive analysis of different threads

可以看到了多了个release后报错了。


5.2 无界信号量

它不检查release的上限情况,只是单纯的加减计数器。

An article will give you a comprehensive analysis of different threads

可以看到虽然多了个release,但是没有问题,而且信号量的数量不受限制。


6.Event

线程间通信,通过线程设置的信号标志(flag)的False 还是True来进行操作,常见方法有:

event.set()      flag设置为True
event.clear()  flag设置为False
event.is_set()  flag是否为True,如果 event.isSet()==False将阻塞线程;
设置等待flag为True的时长,None为无限等待。等到返回True,未等到超时则返回False
event.wait(timeout=None)
Copy after login

下面通过一个例子具体讲述:

import time
e=t.Event()
def ff(num):
  while True:
    if num<5:
      e.clear()   #清空信号标志
      print(&#39;清空&#39;)
    if num>=5:
      e.wait(timeout=1) #等待信号标志为真
      e.set()
      print(&#39;启动&#39;)
      if e.isSet(): #如果信号标志为真则清除标志
        e.clear()
        print(&#39;停止&#39;)
    if num==10:
      e.wait(timeout=3)
      e.clear()
      print(&#39;退出&#39;)
      break
    num+=1
    time.sleep(2)
ff(1)
Copy after login

An article will give you a comprehensive analysis of different threads

设置延迟后可以看到效果相当明显,我们让他干什么事他就干什么事。


7.local

可以为各个线程创建完全属于它们自己的变量(线程局部变量),而且它们的值都在当前调用它的线程当中,以字典的形式存在。下面我们来看下:

l=t.local()  #创建一个线程局部变量
def ff(num):
  l.x=100  #设置l变量的x方法的值为100
  for y in range(num):
    l.x+=3 #改变值
  print(str(l.x))


for y in range(10):
  t.Thread(target=ff,args=(y,)).start() #开始执行线程
Copy after login

那么,可以将变量的x方法设为全局变量吗?我们来看下:

An article will give you a comprehensive analysis of different threads

可以看出他报错了,产生错误的原因是因为这个类中没有属性x,我们可以简单的理解为局部变量就只接受局部。


8.Timer

设置定时计划,可以在规定的时间内反复执行某个方法。他的使用方法是:

t.Timer(num,func,*args,**kwargs) #在指定时间内再次重启程序
Copy after login

下面我们来看下:

def f():
  print(&#39;start&#39;)
  global t #防止造成线程堆积导致最终程序退出
  tt= t.Timer(3, f)
  tt.start()
f()
Copy after login

这样就达到了每三秒执行一次f函数的效果。


总结

通过对线程的全面解析我们了解到了线程的重要性,它可以将我们复杂的问题变得简单化,对于喜欢玩爬虫的小伙伴们可以说是相当有用了,本文基本覆盖了线程的所有概念,希望能帮到大家。

The above is the detailed content of An article will give you a comprehensive analysis of different threads. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles