在实现多线程业务时,如果没有涉及到共享数据处理的业务,还是使用局部变量,必将,在处理共享数据时,还是需要加锁;线程与线程间的局部变量相互独立,变量的处理互补干扰。
在多线程的场景下,针对线程中的局部变量,如果需要让其他业务操作此变量时,此时
局部变量相对当前线程来讲,是全局变量;
局部变量相对其他线程来讲,是局部变量;
为了实现当前线程的局部变量被部分业务处理时,以两个小例子说明下
示例 1:自定义全局变量,以当前线程做为 key
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from threading import current_thread, Thread
global_variable = {}
def handler():
std = global_variable[current_thread()]
print 'Hello {} and this thread\'s name is {}'.format(std, current_thread().name)
def test_thread(name):
global_variable[current_thread()] = name
handler()
t1 = Thread(target=test_thread, args=('Kobe', ), name='thread_kobe')
t2 = Thread(target=test_thread, args=('TMC', ), name='thread_tmc')
t1.start()
t2.start()
t1.join()
t2.join()
print global_variable
print 'end......'
运行结果:
Hello Kobe and this thread's name is thread_kobe
Hello TMC and this thread's name is thread_tmc
{<Thread(thread_kobe, stopped 123145306509312)>: u'Kobe', <Thread(thread_tmc, stopped 123145310715904)>: u'TMC'}
end......
这样,当前线程的数据不会被其他线程捕捉和处理,但是不建议这么做,毕竟 threading
模块提供了 local
示例 2:使用 local
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from threading import current_thread, Thread, local
local_variable = local()
def handler():
std = local_variable.name
print 'Hello {} and this thread\'s name is {}'.format(std, current_thread().name)
def test_thread(name):
local_variable.name = name
handler()
t1 = Thread(target=test_thread, args=('Kobe', ), name='thread_kobe')
t2 = Thread(target=test_thread, args=('TMC', ), name='thread_tmc')
t1.start()
t2.start()
t1.join()
t2.join()
print local_variable
print 'end......'
运行结果如下:
Hello Kobe and this thread's name is thread_kobe
Hello TMC and this thread's name is thread_tmc
<thread._local object at 0x10f3d36b0>
end......
参考
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。