Actual case :
We have achieved a web Video surveillance server , The server collects camera data , The client uses the browser to go through http Request to receive data . The server uses push (multipart/x-mixed-replace) Always use one tcp The connection passes data to the client . This method will continue to occupy a thread , As a result, the single threaded server cannot process multi client requests .
Rewriting procedures , One client request is processed in each thread , Support multi client access .
Solution :
threading.local Function can create thread local data space , Its lower attributes exist independently for each thread , There is no interference between multiple threads .
Simple use of thread local data
import threading
# Create local data for the thread
l = threading.local()
# Yes l Add any attribute, which is the local data of the thread ,
# x Is the local data of the main thread , Other threads cannot access l Under the x
l.x = 1
def f():
print(l.x)
# Called on this thread x
f()
# Run in a child thread f()
# threading.Thread(target=f).start()
# You can see that an exception is thrown and cannot be found x attribute , All used in child threads l I can't access x Of .
# AttributeError: '_thread._local' object has no attribute 'x'
# modify f(), Let him do it l.x modify
def f2():
l.x = 5
# Start the child thread to run f2
threading.Thread(target=f2).start()
# Access again in the main thread l.x, It can be seen that there is still no change or 1, Explain each thread x It's independent
print(l.x)