Home > Backend Development > Python Tutorial > Shared variables and thread.Lock

Shared variables and thread.Lock

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-05 22:27:10
forward
1112 people have browsed it

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template