程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses thread local data and threading Introduction to local library

編輯:Python

1、 How to use thread local data ?

    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 .

2、 Code demonstration

         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)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved