Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

thread local in python #4

Open
TheBigFish opened this issue Nov 13, 2018 · 0 comments
Open

thread local in python #4

TheBigFish opened this issue Nov 13, 2018 · 0 comments
Assignees
Labels

Comments

@TheBigFish
Copy link
Owner

thread local in python

参考 Thread Locals in Python: Mostly easy

线程局部变量

import threading

mydata = threading.local()
mydata.x = 'hello'

class Worker(threading.Thread):
    def run(self):
        mydata.x = self.name
        print mydata.x

w1, w2 = Worker(), Worker()
w1.start(); w2.start(); w1.join(); w1.join()
Thread-1
Thread-2

各线程独享自己的变量,但是使用全局变量 mydata

主线程也有自己的线程局部变量

import threading

mydata = threading.local()
mydata.x = {}

class Worker(threading.Thread):
    def run(self):
        mydata.x['message'] = self.name
        print mydata.x['message']
w1, w2 = Worker(), Worker()
w1.start(); w2.start(); w1.join(); w2.join()
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "E:/learn/python/test/thread_local.py", line 15, in run
    mydata.x['message'] = self.name
AttributeError: 'thread._local' object has no attribute 'x'

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "E:/learn/python/test/thread_local.py", line 15, in run
    mydata.x['message'] = self.name
AttributeError: 'thread._local' object has no attribute 'x'

线程 w1,w2 没有 x 属性,子线程与主线程拥有各自的变量

继承 threading.local

import threading

class MyData(threading.local):
    def __init__(self):
        self.x = {}

mydata = MyData()

class Worker(threading.Thread):
    def run(self):
        mydata.x['message'] = self.name
        print mydata.x['message']

w1, w2 = Worker(), Worker()
w1.start(); w2.start(); w1.join(); w2.join()
Thread-1
Thread-2

应用实例

bottle 0.4.10

class Request(threading.local):
    """ Represents a single request using thread-local namespace. """

    def bind(self, environ):
        """ Binds the enviroment of the current request to this request handler """
        self._environ = environ
        self._GET = None
        self._POST = None
        self._GETPOST = None
        self._COOKIES = None
        self.path = self._environ.get('PATH_INFO', '/').strip()
        if not self.path.startswith('/'):
            self.path = '/' + self.path

#----------------------
request = Request()
#----------------------


def WSGIHandler(environ, start_response):
    """The bottle WSGI-handler."""
    global request
    global response
    request.bind(environ)
    response.bind()
    try:
        handler, args = match_url(request.path, request.method)
        if not handler:
            raise HTTPError(404, "Not found")
        output = handler(**args)
    except BreakTheBottle, shard:
        output = shard.output
@TheBigFish TheBigFish self-assigned this Nov 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant