views:

60

answers:

5

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.

+3  A: 

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.

Amber
A: 

This is fine because you have only one writer thread. Read only operations are always thread-safe. The exception to this arises when you are reading more than one related value and expecting some form of consistency between them. Since writes can happen at any time, reads of multiple values may not be consistent and indeed may not even have any sensible program state at all. In this case, locks are used to make the multiple reads appear to happen as a single atomic operation exclusive to any writes.

Eloff
A: 

It's safe only because it's not especially critical. Weird things like the value not updating when it should won't matter. It is very hard to get a definitive answer on what happens when you pretend a single int that's being read and written to is "atomic", as it depends on the exact architecture and a bunch of other things. But it won't do anything worse than give the wrong number sometimes, so go ahead... or use a queue. :)

Scott Stafford
+1  A: 

It's quite safe.

When the count increases from n to n+1 the "n+1 object" is created and then count is switched from referring to the "n object" to the new "n+1 object".

There is no stage that count is referring to something other than the "n object" or the "n+1 object"

gnibbler
+1  A: 

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.

Mark