Python: is it safe to read values ​​from an object in a stream?

I have a Python / wxPython program where the GUI is the main stream, and I use a different stream to load data from a file. Sometimes files are large and slow to load, so I use the wxPulse dialog to indicate progress.

When I upload a file, I count the number of lines that have been read in the count stream, and I show this count in the wxPulse dialog box in the main stream. I get the score in the main thread by reading the same variable that is written by the load stream.

Is it "thread safe"? Could this somehow cause problems? I have been doing this for a while, and so far everything has been fine.

PS. I know that I can use the queue to transfer the invoice, but I am lazy and do not want it if I do not need it.

+4
source share
5 answers

As a rule, until ...

  • You only have one thread written to, and ...
  • It doesn’t matter that the score is kept exactly in sync with the displayed value ...

this is normal.

+5
source

In normal python, this will be safe, since all access to the variables is protected by GIL (Global Interpreter Lock), which means that all access to the variable is synchronized, so only one thread can do this at a time. The only problem is that @Eloff pointed out that you need to read more than one value and need to be consistent - in this case you will need to develop some kind of access control.

+2
source

This is great because you only have one stream of emails. Read-only operations are always thread safe. An exception to this is when you read more than one related value and expect some form of consistency between them. Because writes can occur at any time, reading multiple values ​​can be consistent and may not even have any reasonable state of the program. In this case, locks are used to make multiple readings, which appear to be a single atomic operation, exclusive to any write operation.

+1
source

It is completely safe.

When the counter is incremented from n to n + 1, an "n + 1 object" is created, and then the counter switches with reference to the "n-object" to the new "n + 1 object".

There is no such stage when the counter refers to something other than an "n-object" or "n + 1 object"

+1
source

It is safe only because it is not particularly important. Strange things, such as a value that is not updated when it does not matter. It is very difficult to get a definitive answer to what happens when you pretend to be the only int that reading and writing is "atomic," because it depends on the exact architecture and many other things. But this will not do anything worse than giving the wrong number sometimes, so go ahead ... or use the queue. :)

0
source

All Articles