多线程抢占问题

import time
import threading obj = 5 def task(arg):
global obj
obj = arg
time.sleep(1)
print(obj) for i in range(6):
t = threading.Thread(target=task, args=(i,))
t.start() # 结果
5
5
5
5
5
5

  

threading.local对象避免线程抢占

为每个线程开辟一块内存空间,存储各自的数据

import time
import threading obj = threading.local() def task(arg):
global obj
obj.value = arg
time.sleep(1)
print(obj.value) for i in range(6):
t = threading.Thread(target=task, args=(i,))
t.start() # 结果
0
3
4
5
2
1

  

模拟threading.local

import time
import threading
# 获取线程的唯一标识
from threading import get_ident class Local():
def __init__(self):
self.storage = {}
def __setitem__(self, key, value):
ident = get_ident()
if ident in self.storage:
self.storage[ident][key] = value
else:
self.storage[ident] = {key:value}
def __getitem__(self, item):
ident = get_ident()
return self.storage[ident][item] obj = Local() def task(arg):
obj['num'] = arg
time.sleep(1)
print(obj['num']) for i in range(6):
t = threading.Thread(target=task, args=(i,))
t.start()

  

粒度精确到协程

为每个协程开辟一块内存空间,存储各自的数据

import time
import threading
try:
# 获取协程的唯一标识
from greenlet import getcurrent as get_ident
except Exception as e:
from threading import get_ident class Local():
def __init__(self):
self.storage = {}
def __setitem__(self, key, value):
ident = get_ident()
if ident in self.storage:
self.storage[ident][key] = value
else:
self.storage[ident] = {key:value}
def __getitem__(self, item):
ident = get_ident()
try:
return self.storage[ident][item]
except Exception as e:
return None obj = Local() def task(arg):
obj['num'] = arg
time.sleep(1)
print(obj['num']) for i in range(6):
t = threading.Thread(target=task, args=(i,))
t.start()

  

threading.local学习的更多相关文章

  1. 多线程多进程学习threading,queue线程安全队列,线程间数据状态读取。threading.local() threading.RLock()

    http://www.cnblogs.com/alex3714/articles/5230609.html python的多线程是通过上下文切换实现的,只能利用一核CPU,不适合CPU密集操作型任务, ...

  2. Flask补充--threading.local对象

    目录 Local 局部变量 全局变量 使用threading.local() 自定义threading.local 函数版 面向对象版 通过setattr和getattr实现 每个对象有自己的存储空间 ...

  3. 自定义threading.local

    1.threading相关. # Author:Jesi # Time : 2018/12/28 14:21 import threading import time from threading i ...

  4. Threading.local

    在多线程环境下,每个线程都有自己的数据.一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁. Threading.local可以创建 ...

  5. 网络编程 多线程/socketserver模块/ threading.local

    线程:进程中负责程序执行的执行单元. 多线程:在1个进程中存在多个线程. 进程只是用来把资源集中在一起,而线程才是cpu上的执行单位. 每个进程都会默认有一个控制线程也叫作主线程. 进程之间是竞争关系 ...

  6. 多线程局部变量之threading.local()用法

    假如,开了十个线程并且做同样的一件事,他们需要带着自己的数据进来,完成事情后带着自己的数据出去.如果是并发,同时进来,他们的数据就会混乱. 一般情况,我们加锁就可以了,一个人先进来,先加锁,另一个人过 ...

  7. python之threading.local

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

  8. [Python 多线程] threading.local类 (六)

    在使用threading.local()之前,先了解一下局部变量和全局变量. 局部变量: import threading import time def worker(): x = 0 for i ...

  9. threading.local()方法;线程池

    一,threading.local() import time import threading v = threading.local() def func(arg): # 内部会为当前线程创建一个 ...

随机推荐

  1. 「CF838B」 Diverging Directions

    B. Diverging Directions 题意 给出一个n个点2n-2条边的有向图.n-1条指向远离根方向的边形成一棵树,还有n-1条从非根节点指向根节点的边. q次操作,1修改第x条边权值为y ...

  2. POJ 2672 Tarjan + 缩点 + 拓扑思想

    Going from u to v or from v to u? Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 17383 ...

  3. PHP日志切割shell

    #!/bin/bash#此脚本用于自动分割php日志,error.log#每天00:01执行此脚本 将前一天的errors.log重命名为errors-xxxx-xx-xx.log格式,并重新打开日志 ...

  4. PHP基础学习----函数

    一.函数的定义 function 函数名([参数1,参数2,参数3,...]){ 函数体: [return 返回值;] } //函数调用 函数名([参数1,参数2,参数3,...]): 二.可变函数 ...

  5. 牛客练习赛28 B数据结构(线段树)

    链接:https://www.nowcoder.com/acm/contest/200/B来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言5242 ...

  6. NoSQL还是SQL?这一篇讲清楚

    https://mp.weixin.qq.com/s?__biz=MzAwMDU1MTE1OQ==&mid=2653550127&idx=1&sn=93f79e007d757a ...

  7. HEOI2013 Segment

    传说中的“李超树”. 大意:给你若干线段,试求横坐标x上的最上方一条线段的编号.无则输出零. 解:用线段树维护. 插入的时候保存自己这个区间上可能成为最大值的线段,被抛弃的则看情况下放. 查询时从最底 ...

  8. python datetime 字符串 时间戳

    #把datetime转成字符串 def datetime_toString(dt): return dt.strftime("%Y-%m-%d-%H") #把字符串转成dateti ...

  9. 在gitlab新建空项目,将本地的git仓库的内容上传

    gitlab新建了这个项目. 按照官网的步骤上传代码 一:将本地代码上传到本地仓库 1.进入项目文件夹 git init 2.项目代码添加到本地git git add . 3.提交到stage区域 g ...

  10. Luogu P2580 于是他错误的点名开始了 Trie树 字典树

    字典树裸题.每次插入询问串,查询的时候拿出来直接查,信息保留在节点上. #include <bits/stdc++.h> using namespace std; char s[51]; ...