How to use two threads (GUI and backend)

Marko Rauhamaa marko at pacujo.net
Wed Oct 26 08:58:45 EDT 2016


pozz <pozzugno at gmail.com>:

> Il 26/10/2016 13:27, Antoon Pardon ha scritto:
>> Op 26-10-16 om 12:22 schreef pozz:
>>> Is it safe to access this variable from two different threads?
>>> Should I implement a safer and more complex mechanism? If yes, what
>>> mechanism?
>>
>> Accessing from multiple thread shouldn't be a problem. As long as you
>> only change it in one thread.
>
> I don't want to doubt what you have written, but... are you
> definitevely sure? I tried to search for some authoritative
> documentation about this topic, but I couldn't find any.

I didn't check but I would guess you are right. That kind of
authoritative statement is not made explicitly. Java, on the other hand,
has been documented nicely:

  <URL: https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jl
  s-17.4.5>

> If the main loop is updating the variable from 0x01020304 to
> 0xA1A2A3A4 and the change happens on a byte basis, the ISR could
> access a completely wrong value, for example 0x0102A3A4.
>
> So the main question here is: does python *specification/standard*
> guarantees atomic operations? If yes, what are they?

Python guarantees that even a pathological Python application program
that only employs ordinary, safe operations cannot crash Python. It
follows (de facto) that "pointers" must be protected against race
conditions and other artifacts. Similarly, you can't render lists, dicts
and other complex data structures incoherent with any ordinary means
regardless of race conditions.

Since Python's integers are (really or conceptually) objects behind
pointers, any Python implementation would be considered out of
compliance if it didn't guarantee either 0x01020304 or 0xa1a2a3a4 in
your example.

In practice, this coherency has been implemented in CPython with a
global lock (GIL). CPython programs are effectively single-threaded.
They only let go of the lock when they are performing a system call.

I can't think of a valid program that could take advantage of this
primitive guarantee of Python's. For example, there is no "volatile" in
Python so you can't coordinate Python threads safely without proper
synchronization. If you set a variable in one thread and read it in
another thread, the latter might never see the change.


Marko



More information about the Python-list mailing list