E
E
Eugene-1232021-02-02 12:20:50
Python
Eugene-123, 2021-02-02 12:20:50

Why is reference counting NOT thread safe?

I read here that python uses the GIL and one of the reasons is the fact that references to each object are counted and it's not thread safe. Why is reference counting not safe? I also read that:

The problem that the GIL solves is that in a multi-threaded application, multiple threads can increment or decrement this reference count at the same time. This can lead to the fact that the memory is cleaned up incorrectly and the object to which the reference still exists is deleted.
How can this happen? Do I understand correctly that if two threads accidentally perform something like counter++at the same time, then the counter increases not by 2, but by 1?
And further:
But adding a lock to multiple objects can lead to another problem - deadlocks, which only happen if there is a lock on more than one object. In addition, this problem would also reduce performance due to the repeated installation of blockers.

Explain what is the point here? And what is the performance degradation? Is it because you just set some kind of flag there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-02
@Eugene-123

The task is to increase the value of X by 1. Let's say there are two threads, each performs two actions: get the value and increase it by 1.
Option 1:
The first thread receives this value, it is equal to 0
The first thread increases this value (0), it is equal to 1
The second thread gets this value, it is 1
The second thread increments this value (1), it is 2
Case 2:
The first thread gets this value, it is 0
The second thread gets this value, it is 0
The first thread increments this value (0) , it is equal to 1
The second thread increments this value (0), it is equal to 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question