What is “thread local storage” in Python, and why do I need it?

前端 未结 5 1854
清酒与你
清酒与你 2020-11-28 19:58

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

Although I have used threading.Thread before I never really understood or saw examp

5条回答
  •  春和景丽
    2020-11-28 20:32

    I may be wrong here. If you know otherwise please expound as this would help explain why one would need to use thread local().

    This statement seems off, not wrong: "If you want to atomically modify anything that another thread has access to, you have to protect it with a lock." I think this statement is ->effectively<- right but not entirely accurate. I thought the term "atomic" meant that the Python interpreter created a byte-code chunk that left no room for an interrupt signal to the CPU.

    I thought atomic operations are chunks of Python byte code that does not give access to interrupts. Python statements like "running = True" is atomic. You do not need to lock CPU from interrupts in this case (I believe). The Python byte code breakdown is safe from thread interruption.

    Python code like "threads_running[5] = True" is not atomic. There are two chunks of Python byte code here; one to de-reference the list() for an object and another byte code chunk to assign a value to an object, in this case a "place" in a list. An interrupt can be raised -->between<- the two byte-code ->chunks<-. That is were bad stuff happens.

    How does thread local() relate to "atomic"? This is why the statement seems misdirecting to me. If not can you explain?

提交回复
热议问题