Home  >  Article  >  Backend Development  >  How to define thread local variables in python

How to define thread local variables in python

(*-*)浩
(*-*)浩Original
2019-07-04 13:54:332939browse

There is a concept called thread local variables. Generally, we lock global variables in multi-threads. These variables are shared variables. Each thread can read and write variables. In order to maintain synchronization, we will do shackle processing.

How to define thread local variables in python

But after some variables are initialized, we just want them to always exist in each thread, which is equivalent to a shared variable within a thread, and between threads It is isolated and is a local variable. The python threading module provides such a class, called local. (Recommended learning: Python video tutorial)

When using local variables, you need to pass parameters. For example, there is an example where the program needs to process customer applications. For a customer, a new thread is opened for processing, and the customer has attributes (parameters) such as name, age, gender, etc. It is very cumbersome to pass parameters if they all need to be passed. Python provides the threading.local module to facilitate the transfer of thread local variables. Look directly at the following example:

# /usr/bin/env python
# coding:utf-8


import threading

# Threading.local对象
ThreadLocalHelper = threading.local()
lock = threading.RLock()

class MyTheadEx(threading.Thread):
    def __init__(self, threadName, name, age, sex):
        super(MyTheadEx, self).__init__(name=threadName)
        self.__name = name
        self.__age = age
        self.__sex = sex

    def run(self):
        global ThreadLocalHelper
        ThreadLocalHelper.ThreadName = self.name
        ThreadLocalHelper.Name = self.__name
        ThreadLocalHelper.Age = self.__age
        ThreadLocalHelper.Sex = self.__sex
        MyTheadEx.ThreadPoc()

    # 线程处理函数
    @staticmethod
    def ThreadPoc():
        lock.acquire()
        try:
            print 'Thread={id}'.format(id=ThreadLocalHelper.ThreadName)
            print 'Name={name}'.format(name=ThreadLocalHelper.Name)
            print 'Age={age}'.format(age=ThreadLocalHelper.Age)
            print 'Sex={sex}'.format(sex=ThreadLocalHelper.Sex)
            print '----------'
        finally:
            lock.release()

if __name__ == '__main__':
    Tom = {'Name': 'tom', 'Age': 20, 'Sex': 'man'}
    xiaohua = {'Name': 'xiaohua', 'Age': 18, 'Sex': 'woman'}
    Andy = {'Name': 'Andy', 'Age': 40, 'Sex': 'man'}
    T = (Tom, xiaohua, Andy)
    threads = []
    for i in range(len(T)):
        t = MyTheadEx(threadName='id_{0}'.format(i), name=T[i]['Name'], age=T[i]['Age'], sex=T[i]['Sex'])
        threads.append(t)
    for i in range(len(threads)):
        threads[i].start()
    for i in range(len(threads)):
        threads[i].join()
    print 'All Done!!!'

It can be seen that each thread can read and write the threading.local object without interfering with each other. Reasonable use of threading.local can greatly simplify the code logic while ensuring the data security of each sub-thread. The biggest use of Threading.local is to bind user information when making HTTP requests, so that each user thread can easily access their own resources without interfering with each other.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to define thread local variables in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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