当前位置:网站首页>[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
边栏推荐
- Database full stack Engineers (devdbops) have low down payment and high return, and pay after employment
- Huawei atlas900 reveals the secret: it integrates thousands of shengteng 910 chips, and its computing power is comparable to 500000 PCs!
- 【HCIP】OSPF 关系建立
- Science | University of Washington uses AI and structural prediction to design new proteins
- 中兴通讯:5G基站在全球发货已超过5万个!
- 云原生微服务第一章之服务器环境说明
- STM32 how to use serial port
- Apifox--比 Postman 还好用的 API 测试工具
- 利用Go制作微信机器人(一)发送消息
- 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
猜你喜欢

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

华裔科学家Ashe教授对涉嫌造假的Nature论文的正面回应
![[hcip] OSPF relationship establishment](/img/19/e03fea44f2908c7b585e7a1f87c075.png)
[hcip] OSPF relationship establishment

HCIA-R&S自用笔记(19)VLAN配置及实验、VLAN间路由

Cached database for memcached

Professor Ashe, a Chinese scientist, made a positive response to the suspected fake Nature paper

PostgreSQL and Navicat: the backbone of the database industry

【HCIP】OSPF 路由计算

Apifox--比 Postman 还好用的 API 测试工具

科研太忙无法顾家?陈婷:人生不能只有一个支点
随机推荐
麒麟990系列为何无缘Cortex-A77和Mali G77?
Luo Xu talks with Siemens wanghaibin: advanced manufacturing requires benefits from Digitalization
功耗降低、功能升级!启英泰伦发布二代语音AI芯片:模组价格低至14.99元!
Is test development development development?
菜鸟网络面试【杭州多测师】【杭州多测师_王sir】
Let the program do one thing in one or more seconds
Too busy with scientific research to take care of your family? Chen Ting: life cannot have only one fulcrum
测试开发是开发吗?
Hcia-r & s self use notes (23) DHCP
Lighting 5g in the lighthouse factory, Ningde era is the first to explore the way made in China
Why did kylin 990 series fail to meet cortex-a77 and Mali G77?
研究阿尔茨海默病最经典的Nature论文涉嫌造假
基于gRPC编写golang简单C2远控
基于C语言设计的增量型安全文件系统 SFS
面试:你印象最深的BUG,举个例子
After closing the Suzhou plant, Omron Dongguan plant announced its dissolution, and more than 2000 people are facing unemployment!
Plato Farm有望通过Elephant Swap,进一步向外拓展生态
TypeScript阶段学习
[hcip] OSPF relationship establishment
sql多表查询的练习