在使用threading.local()之前,先了解一下局部变量和全局变量。

局部变量:

import threading
import time def worker():
x = 0
for i in range(100):
time.sleep(0.0001)
x += 1
print(threading.current_thread(),x) for i in range(10):
threading.Thread(target=worker).start() 运行结果:
<Thread(Thread-2, started 123145372971008)> 100
<Thread(Thread-6, started 123145393991680)> 100
<Thread(Thread-1, started 123145367715840)> 100
<Thread(Thread-3, started 123145378226176)> 100
<Thread(Thread-5, started 123145388736512)> 100
<Thread(Thread-7, started 123145399246848)> 100
<Thread(Thread-4, started 123145383481344)> 100
<Thread(Thread-10, started 123145415012352)> 100
<Thread(Thread-8, started 123145404502016)> 100
<Thread(Thread-9, started 123145409757184)> 100

  上面例子使用多线程,每个子线程完成不同的计算任务,x是局部变量。

每个子线程都要压栈,每个栈是独立的空间。每次压栈,局部变量x的作用域地址是不同的(线程独享),计算结果互不干扰。

全局变量:

使用global:

import threading
import time x = 0
def worker():
global x
x = 0
for i in range(100):
time.sleep(0.0001)
x += 1
print(threading.current_thread(),x) for i in range(10):
threading.Thread(target=worker).start() 运行结果:
<Thread(Thread-2, started 123145483571200)> 888
<Thread(Thread-5, started 123145499336704)> 908
<Thread(Thread-3, started 123145488826368)> 930
<Thread(Thread-4, started 123145494081536)> 937
<Thread(Thread-1, started 123145478316032)> 941
<Thread(Thread-6, started 123145504591872)> 947
<Thread(Thread-7, started 123145509847040)> 949
<Thread(Thread-8, started 123145515102208)> 955
<Thread(Thread-9, started 123145520357376)> 962
<Thread(Thread-10, started 123145525612544)> 964

  上面例子中当主线程中x是全局变量时,就变成了公共资源(也就是同一个对象),每个子线程互相干扰,最终导致错误的计算结果。

Python提供了 threading.local 类,将这个类实例化得到一个全局对象,但是不同的线程使用这个对象存储的数据其它线程不可见(本质上就是不同的线程使用这个对象时为其创建一个独立的字典)。

使用threading.local() :

import threading
import time # class A:
# def __init__(self,x):
# self.x = x
# a = A(0) a = threading.local()#全局对象 def worker():
a.x = 0
for i in range(100):
time.sleep(0.0001)
a.x += 1
print(threading.current_thread(),a.x) for i in range(10):
threading.Thread(target=worker).start() 运行结果:
<Thread(Thread-4, started 123145570172928)> 100
<Thread(Thread-6, started 123145580683264)> 100
<Thread(Thread-1, started 123145554407424)> 100
<Thread(Thread-2, started 123145559662592)> 100
<Thread(Thread-8, started 123145591193600)> 100
<Thread(Thread-5, started 123145575428096)> 100
<Thread(Thread-3, started 123145564917760)> 100
<Thread(Thread-7, started 123145585938432)> 100
<Thread(Thread-10, started 123145601703936)> 100
<Thread(Thread-9, started 123145596448768)> 100

  每个子线程使用全局对象a,但每个线程定义的属性a.x是该线程独有的。

举一个错误的例子:,主线程中使用threading.local定义本地变量x,x在主线程中是独有的,子线程中就访问不到主线程的x的属性。

import threading

X='abc'
ctx=threading.local()
ctx.x=123 #主线程中定义x本地属性
print(ctx,type(ctx),ctx.x) def work():
print(X)
print(ctx)
print(ctx.x) #子线程访问不到
print('Good job') threading.Thread(target=work).start()
运行结果:
<_thread._local object at 0x10407bd00> <class '_thread._local'> 123
abc
<_thread._local object at 0x10407bd00>
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Users/ihoney/Python/test_4.py", line 12, in work
print(ctx.x)
AttributeError: '_thread._local' object has no attribute 'x'

  ctx全局对象对主线程和子线程都是可以使用的,主线程定义了属性x,但子线程在尝试访问属性x时,就相当于访问自己线程内的属性x,而自己线程并没有定义,就会抛出AttributeError异常:'_thread._local' object has no attribute 'x'。

[Python 多线程] threading.local类 (六)的更多相关文章

  1. python之threading.local

    简述: threading.local是全局变量但是它的值却在当前调用它的线程当中 作用: 在threading module中,有一个非常特别的类local.一旦在主线程实例化了一个local,它会 ...

  2. python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...

  3. 再看python多线程------threading模块

    现在把关于多线程的能想到的需要注意的点记录一下: 关于threading模块: 1.关于 传参问题 如果调用的子线程函数需要传参,要在参数后面加一个“,”否则会抛参数异常的错误. 如下: for i ...

  4. Python多线程 - threading

    目录 1. GIL 2. API 3. 创建子线程 4. 线程同步 4.1. 有了GIL,是否还需要同步? 4.1.1. 死锁 4.1.2. 竞争条件 4.1.3. GIL去哪儿了 4.2. Lock ...

  5. python:threading.Thread类的使用详解

    Python Thread类表示在单独的控制线程中运行的活动.有两种方法可以指定这种活动: 1.给构造函数传递回调对象 mthread=threading.Thread(target=xxxx,arg ...

  6. [转]python 多线程threading简单分析

    多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的 ...

  7. 多线程threading.local的作用及原理?

    1.示例代码 import time import threading v = threading.local() def func(arg): # 内部会为当前线程创建一个空间用于存储:phone= ...

  8. python多线程threading

    本文通过 4个example 介绍python中多线程package —— threading的常用用法, 包括调用多线程, 同步队列类Queue, Ctrl+c结束多线程. example1. 调用 ...

  9. python多线程安全local()

    import time import threading from threading import local class Foo(local): pass # 实例化(创建)对象 foo = Fo ...

随机推荐

  1. java.sql.SQLException: Io 异常: Invalid number format for port number

    java.sql.SQLException: Io 异常: Invalid number format for port number   jdbc数据库链接配置没有写端口号 ​ 要检查jdbc的配置 ...

  2. VMwear安装Centos7详细过程

      1.软硬件准备软件:推荐使用VMwear,我用的是VMwear 10镜像:CentOS7   硬件:因为是在宿主机上运行虚拟化软件安装centos,I3CPU双核.硬盘500G.内存4G以上. 2 ...

  3. tomcat-虚拟目录的映射

    虚拟目录的映射 1.新建 ${tomcat安装目录}\conf\Catalina\localhost\xxx.xml 文件. 文件内容: <Context  path="/xxx&qu ...

  4. Java学习笔记(3)----网络套接字服务器多线程版本

    本例给出一个客户端程序和一个服务器程序.客户端向服务器发送数据.服务器接收数据,并用它来生成一个结果,然后将这个结果返回给客户端.客户端在控制台上显示结果.在本例中,客户端发送的数据是圆的半径,服务器 ...

  5. LDAP 原理图解

    来自为知笔记(Wiz)

  6. SQLSERVER的逆向工程,将数据库导入到PowerDesigner中

    原文:http://blog.csdn.net/linianzhenti/article/details/42938595 PD是一款不错的数据库设计工具,在佩特来这个项目中,起初,合作伙伴用PD大体 ...

  7. _tcsrchr

    原文:http://www.cnblogs.com/diyunpeng/archive/2012/01/18/2325289.html _tcsrchr #include <afx.h> ...

  8. 仿小米便签图文混排 EditText解决尾部插入文字bug

    一直想实现像小米便签那样的图文混排效果,收集网上的办法无非三种: 1.自定义布局,每张图片是一个ImageView,插入图片后插入EditText,缺点是实现复杂,不能像小米便签那样同时选中图片和文字 ...

  9. 自定义BaseActivity

    思路很简单:将软件里用到的大量重复的页面布局抽象出来,编写成一个抽象的Activity类,然后在实现具体页面时继承它,并且在主内容空白区填入需要的内容. 例如在最近开发的一款资讯类应用中,每张页面上面 ...

  10. 微信小程序开发8-小程序的宿主环境(1)

    1.小程序的运行环境分成渲染层和逻辑层,第2章提到过 WXML 模板和 WXSS 样式工作在渲染层,JS 脚本工作在逻辑层.小程序的渲染层和逻辑层分离是经过很多考虑得出来的模型 2. 1.渲染层和数据 ...