什么是“线程本地存储"?在Python中,为什么我需要它? [英] What is "thread local storage" in Python, and why do I need it?

查看:126
本文介绍了什么是“线程本地存储"?在Python中,为什么我需要它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是在Python中,如何在线程之间共享变量?

In Python specifically, how do variables get shared between threads?

尽管我在从未真正理解或看到过如何共享变量的示例之前就使用过threading.Thread.它们是在主线程和子线程之间共享还是仅在子线程之间共享?我什么时候需要使用线程本地存储来避免这种共享?

Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?

我已经看到许多关于通过使用锁在线程之间同步访问共享数据的警告,但是我还没有看到一个很好的问题示例.

I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem.

提前谢谢!

推荐答案

在Python中,所有内容都是共享的,但函数局部变量除外(因为每个函数调用都有自己的局部变量集,并且线程始终是单独的函数调用. )即使这样,也只有变量本身(引用对象的名称)才是函数的局部变量.对象本身始终是全局的,任何事物都可以引用它们. 在这方面,特定线程的Thread对象不是特殊对象.如果将Thread对象存储在所有线程都可以访问的位置(例如全局变量),则所有线程都可以访问该Thread对象.如果您想自动修改另一个线程可以访问的任何内容,则必须使用锁来保护它.当然,所有线程必须共享这个非常相同的锁,否则效果不是很好.

In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them. The Thread object for a particular thread is not a special object in this regard. If you store the Thread object somewhere all threads can access (like a global variable) then all threads can access that one Thread object. If you want to atomically modify anything that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.

如果要使用实际的线程本地存储,则在其中输入threading.local.threading.local的属性在线程之间不共享.每个线程仅看到其自身放置在其中的属性.如果您对它的实现感到好奇,请在 _threading_local.py中找到源. 在标准库中.

If you want actual thread-local storage, that's where threading.local comes in. Attributes of threading.local are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in _threading_local.py in the standard library.

这篇关于什么是“线程本地存储"?在Python中,为什么我需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆