Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: safe to read values from an object in a thread?

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

As I load the file, I count the number of lines that have been read in the counting thread, and I display this count in the wxPulse dialog in the main thread. I get the count in the main thread by reading the same variable that is being written to by the loading thread.

Is this "thread safe"? Could this somehow cause problems? I've been doing it for awhile and it has been fine so far.

PS. I know I could use a queue to transfer the count, but I'm lazy and don't want to if I don't have to.

like image 645
gaefan Avatar asked Sep 15 '10 04:09

gaefan


2 Answers

Generally as long as...

  • You only have one thread writing to it, and...
  • It's not important that the count be kept precisely in sync with the displayed value...

it's fine.

like image 194
Amber Avatar answered Oct 01 '22 00:10

Amber


In normal python this will be safe as all access to variables are protected by the GIL(Global Interpreter Lock) this means that all access to a variable are syncronised so only one thread can do this at a time. The only issue is as @Eloff noted if you need to read more than one value and need them to be consistent - you will need to design in some control of access in this case.

like image 41
mmmmmm Avatar answered Oct 01 '22 01:10

mmmmmm