Nine .Flask local and partial function

A local and partial function

1. local

local multiple threads to modify the same data, multiple copies to each thread with a variable, 
such as our use of the request, how to make different requests has its own request. It is to open up a space for data storage for each thread

  threading.local [no relation] and flask
  role: to create a separate space for each thread so that the thread of their own space in the data operation (data isolation).

  Not threading.local

from threading import Thread
import time
ctx = -1
def task(arg):
    global ctx
    ctx = arg
    # time.sleep(2)
    print(ctx)

for i in range(5):
    t = Thread(target=task,args=(i,))
    t.start()

# 0
# 1
# 2
# 3
# 4

 Use threading.local

from threading import Thread,local
# 特殊的对象
ctx = local()
def task(arg):
    ctx.value = arg
    # time.sleep(2)
    print(ctx.value)
for i in range(5):
    t = Thread(target=task,args=(i,))
    t.start()

    # 0
    # 1
    # 2
    # 3
    # 4
import threading
from threading import local
def task(i):
    print(threading.get_ident(),i)    #  获取每个线程唯一id

for i in range(5):
    t = threading.Thread(target=task,args=(i,))
    t.start()
    
# 14896 0
# 10780 1
# 3356 2
# 11384 3
# 14308 4
import threading
from threading import local
import time
obj = local()
def task(i):
    obj.xxxxx = i
    print(threading.get_ident(), obj.xxxxx,"拉拉")
    time.sleep(2)
    # print(obj.xxxxx,i)
    print(threading.get_ident(),i,"哈哈")

for i in range(5):
    t = threading.Thread(target=task,args=(i,))
    t.start()
# 62320 Lara 
# 43481 Lara 
# 70842 Lara 
# 9723 Lara 
# 65604 Lara 
# 62320 ha 
# 65604 ha 
# 9723 ha 
# 43481 ha 
# 70842 ha
 
 
By custom dictionary threading.local (function) method
import time
import threading
import greenlet
DIC = {}
def task(i):
    # ident = threading.get_ident()
    ident = greenlet.getcurrent()
    if ident in DIC:
        DIC[ident]['aa'] = i
    else:
        DIC[ident] = {'aa':i }
    time.sleep(2)

    print(DIC[ident]['aa'],i)

for i in range(5):
    t = threading.Thread(target=task,args=(i,))
    t.start()
    print(DIC)
 
 

 





 

 

 

 

 

Guess you like

Origin www.cnblogs.com/lovershowtime/p/11747169.html