Home  >  Article  >  Backend Development  >  Shared variables and thread.Lock

Shared variables and thread.Lock

WBOY
WBOYforward
2024-02-05 22:27:101044browse

Shared variables and thread.Lock

Question content

In Java, the value of a shared variable in a thread can become stalled unless you use atomic operations or other thread synchronization mechanisms.

Given the GIL in CPython. I see value in Lock inc where: Even in the confusing a = 1 idiom, there are multiple steps performed before the assignment. To prevent race conditions.

But in a case like a = 1, there is no lock. After a thread updates a, is it possible to have threads A and B read different values ​​of a?

Another way to ask this question is, does Lock ensure shared value propagation, whereas the absence of Lock does not?


Correct answer


The problem is not that a = 1. If the only thing you do in your entire code is set a to various values, then you don't need a lock.

However, if you are setting a = 1 while somewhere else in your code is doing a = a 1, then you need to lock them. You lock a = 1 so that if someone else increments a, it will happen exactly before or after you set a.

So in almost all cases, unless you really know what you are doing, a lock is the simplest solution.

The above is the detailed content of Shared variables and thread.Lock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete