当前位置:网站首页>[flask advanced] analyze the thread isolation mechanism in flask in combination with the source code
[flask advanced] analyze the thread isolation mechanism in flask in combination with the source code
2022-07-26 23:06:00 【Hall owner a Niu】
Personal profile
- Author's brief introduction : Hello everyone , I'm Daniel , New star creator of the whole stack .
- Blogger's personal website : A Niu's blog house
- Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
- Series column :flask Framework quick start
- Maxim : To be light , Because there are people who are afraid of the dark !

I found a good AI learning website a few days ago , Easy to understand , Humor and wit humor , I can't help but share it with you .
Click to jump to the website : AI learning
Catalog
Preface
We wrote in the previous introductory series request Object mentioned this request In fact, it is a multi-threaded mechanism , As a global variable , How does it achieve that each thread in a multithread does not affect each other , Thread safe , This article will combine source code analysis flask Thread isolation mechanism in !
Question elicitation
First, let's explain thread isolation , He means that the threads in a process do not affect each other at runtime , Like the following code :
import threading
class B:
a = 0
b = B()
def func():
b.a += 1
print(" Threads 1 : a = " + str(b.a) + "\n")
new_t = threading.Thread(target=func)
new_t.start()
b.a += 1
print(" The main thread : a = " + str(b.a))

You can see ,a Global variable , Main thread and thread pair variables a The influence of is mutual , Not isolated , Corresponding to flask in ,request Is a global variable , It is possible to accept many network requests at the same time , To start multiple threads . In order to make request The correct point is its instantiation Request object , Ensure that requests do not interfere with each other , Thread isolation mechanism is very important ! Let's take a look flask Thread isolation mechanism in !
flask Thread isolation implementation in
As we can think , We can use python Dictionary in this data structure , Like this :
request = {
thread_id1:Request1;
thread_id2:Request2;
...
}
So it's actually flask The interior is similar , It also uses the basic data type of dictionary to realize thread isolation , Let's go and have a look !
Dictionaries can only store data , And we also need to manipulate data , Therefore, it needs to be encapsulated in an object , We introduced flask One of the cores of werkzeug, The implementation of thread isolation we want to see happens to be werkzeug Inside local.py In file :

You can see such a Local object , In fact, it is a package of dictionary principles !
So we use this Local Object to test thread isolation :
import threading,time
from werkzeug.local import Local
b = Local()
b.a = 0
def func():
b.a = 1
print(" Threads 1 : a = " + str(b.a))
new_t = threading.Thread(target=func,name='thread_01')
new_t.start()
time.sleep(1)
b.a += 2
print(" The main thread : a = " + str(b.a))

You can see , We use it Local The instantiated object is thread isolated !
Next, let's continue to look at the previous picture 
Before written _request_ctx_stack and _app_ctx_stack These variables actually point to LocalStack This stack , namely LocalStack Instantiated object !
Now let's finish reading Local after , We also guess this from the name LocalStack Not simple , It is a thread isolated stack !
We can see LocalStack Source code :
You can see LocalStack Isolate objects from threads Local It was packaged , And it provides push,pop, And get the top element of the stack top Method !
Seeing this, we can conclude that :Local Using dictionary to realize thread isolation ,LocalStack Yes Local It is encapsulated to form a thread isolated stack !
Still use LocalStack Write a case to see :
import threading,time
from werkzeug.local import LocalStack
myStack = LocalStack()
myStack.push(1)
print(" In the main thread push after , The value is :" + str(myStack.top))
def fun():
# Thread one
myStack.push(2)
print(" In thread one push after , The value is :" + str(myStack.top))
new_t = threading.Thread(target=fun,name='thread_01')
new_t.start()
time.sleep(1)
# The main thread
print(" Finally, the value of the main thread is :" + str(myStack.top))

You can see that threads do not affect each other !
So flask in AppContext and RequestContext It's also thread isolated ( Because these two contexts are pushed LocalStack), Essentially, when used request when , Thread isolation makes request Can correctly find its instantiation Request!
summary
The significance of using thread isolation lies in : Enable the current thread to correctly reference the object it has created , Instead of referring to objects created by other threads !
From this to push :
Not only request Is thread isolated ,session and g Object is also ( Be careful :flask Core objects of app Not thread isolated , There is only one global , That is to say current_app Thread isolation is meaningless ! and request Instantiate the object Request There are many !)
Conclusion
If you think the blogger's writing is good , You can pay attention to the current column , Bloggers will finish this series ! You are also welcome to subscribe to other good columns of bloggers .
Series column
Soft grinding css
Hard bubble javascript
The front end is practical and small demo
边栏推荐
- 面试官问:JS的this指向
- [paper reading] logan:membership influence attacks against generative models
- 8-其他编程语言--记录
- TypeScript阶段学习
- ZTE: more than 50000 5g base stations have been shipped worldwide!
- Xinding acquires Ziguang holdings! Wanye enterprise: comprehensive transformation of integrated circuits!
- 基本的SELECT语句
- 菜鸟网络面试【杭州多测师】【杭州多测师_王sir】
- Domestic DRAM will be mass produced by the end of the year, but the road ahead is still long!
- 比海豹便宜,造型炸裂空间大,20万左右真没对手?长安全新“王炸”这样选才划算
猜你喜欢

Embedded sig | distributed soft bus

Implementation principle of semaphore in golang

KT6368A蓝牙芯片开发注意事项以及问题集锦--长期更新

Arduino experiment I: two color lamp experiment

Kt6368a Bluetooth chip development precautions and problem collection - long term update

Hcia-r & s self use notes (23) DHCP

Cached database for memcached
![[paper reading] logan:membership influence attacks against generative models](/img/67/0079e8e1513830cb4de9870377b509.png)
[paper reading] logan:membership influence attacks against generative models

gateway基本使用

7.27 watch first | openeuler is ambitious, open source Huizhi creates the future - the most detailed agenda of the Euler sub forum of the open atom global open source summit is released
随机推荐
思立微的反击:汇顶涉案屏下光学指纹专利被宣告无效
Interview: your most impressive bug, for example
SQL 基础知识
Cloud native microservices Chapter 1 server environment description
STM32 how to use serial port
Reinforcement learning weekly 55: lb-sgd, msp-drl & robust reinforcement learning against
Dao:op token and non transferable NFT are committed to building a new digital democracy
After working for one year, I have some insights (written in 2017)
Eureka基本使用
Introduction to Nacos as a registry and configuration center - realize remote call, dynamically obtain configuration files and database configuration information
Hcia-r & s self use notes (21) STP technical background, STP foundation and data package structure, STP election rules and cases
基本的SELECT语句
After closing the Suzhou plant, Omron Dongguan plant announced its dissolution, and more than 2000 people are facing unemployment!
基于C语言设计的增量型安全文件系统 SFS
工作一年后,我有些感悟(写于2017年)
【无标题】
Hcia-r & s self use notes (20) VLAN comprehensive experiment, GVRP
【HCIP】OSPF 路由计算
总投资100亿美元,华虹无锡12吋晶圆厂正式投产
程序员成长第二十九篇:如何激励员工?