ThreadLocal和异步

      多线程环境下,每一个线程均可以使用所属进程的全局变量。如果一个线程对全局变量进行了修改,将会影响到其他所有的线程。为了避免多个线程同时对变量进行修改,引入了线程同步机制,通过互斥锁,条件变量或者读写锁来控制对全局变量的访问只用全局变量并不能满足多线程环境的需求,很多时候线程还需要拥有自己的私有数据,这些数据对于其他线程来说不可见。因此线程中也可以使用局部变量,局部变量只有线程自身可以访问,同一个进程下的其他线程不可访问。

'''

threadlocal就有俩功能:

1、将各自的局部变量绑定到各自的线程中

2、局部变量可以传递了,而且并没有变成形参

'''

import threading

# 创建全局ThreadLocal对象:

local_school = threading.local()

def process_student():

# 获取当前线程关联的student:

std = local_school.student

print('Hello, %s (in %s)' % (std, threading.current_thread().name))

def process_thread(name):

# 绑定ThreadLocal的student:

local_school.student = name

process_student()

t1 = threading.Thread(target=process_thread, args=('yongGe',), name='Thread-A')

t2 = threading.Thread(target=process_thread, args=('老王',), name='Thread-B')

t1.start()

t2.start()



'''

1、将各自的局部变量绑定到各自的线程中

2、局部变量可以传递了,而且并没有变成形参

'''

import threading

# 创建字典对象:

myDict={}

def process_student():

# 获取当前线程关联的student:

std = myDict[threading.current_thread()]

print('Hello, %s (in %s)' % (std, threading.current_thread().name))

def process_thread(name):

# 绑定ThreadLocal的student:

myDict[threading.current_thread()] = name

process_student()

t1 = threading.Thread(target=process_thread, args=('yongGe',), name='Thread-A')

t2 = threading.Thread(target=process_thread, args=('老王',), name='Thread-B')

t1.start()

t2.start()


异步

from multiprocessing import Pool

import time

import os

def test():

print("---进程池中的进程---pid=%d,ppid=%d--" % (os.getpid(), os.getppid()))

for i in range(3):

print("----%d---" % i)

time.sleep(1)

return "老王"

def test2(args):

print('1...')

time.sleep(10)

print("---callback func--pid=%d" % os.getpid())

print("---callback func--args=%s" % args)

print('2...')

if __name__ == '__main__':

pool = Pool(3)

#callback表示前面的func方法执行完,再执行callback,并且可以获取func的返回值作为callback的参数

pool.apply_async(func=test, callback=test2)

#pool.apply_async(func=test)

#模拟主进程在做任务

time.sleep(5)

print("----主进程-pid=%d.....服务器是不关闭的----" % os.getpid())

# while True:

#    pass

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 线程 1.同步概念 1.多线程开发可能遇到的问题 同步不是一起的意思,是协同步调 假设两个线程t1和t2都要对nu...
    TENG书阅读 3,818评论 0 1
  • 1.进程和线程 队列:1、进程之间的通信: q = multiprocessing.Queue()2、...
    一只写程序的猿阅读 4,826评论 0 17
  • 多任务可以由多进程完成,也可以由一个进程内的多线程完成。我们前面提到了进程是由若干线程组成的,一个进程至少有一个线...
    壁花烧年阅读 4,249评论 0 0
  • 本文是笔者学习廖雪峰Python3教程的笔记,在此感谢廖老师的教程让我们这些初学者能够一步一步的进行下去.如果读者...
    相关函数阅读 10,861评论 1 8
  • 基础1.r''表示''内部的字符串默认不转义2.'''...'''表示多行内容3. 布尔值:True、False(...
    neo已经被使用阅读 5,750评论 0 5

友情链接更多精彩内容