Is it possible to read a array value while it is being appended (race condition) #10501
Replies: 5 comments 13 replies
-
I think it is safer implement ring Buffer (or deque class) . Your code don't have any protection against overflow. also non-stop append/pop is not too efficient (memory allocation) for this type of task) |
Beta Was this translation helpful? Give feedback.
-
What version of Micropython are you using, and on what hardware? |
Beta Was this translation helpful? Give feedback.
-
This code is definitely not safe. Concurrent access to mutable data structures (e.g. list) is not allowed across cores. Note that the data structure in question is a list, not an array. You need to use _thread.allocate_lock (https://docs.python.org/3.5/library/_thread.html#_thread.allocate_lock) and then protect the concurrent access.
@robert-hh This is true for multithreading on a single core, protected via the GIL. Like you point out, the GIL would make multi-core multi-threading useless (and this applies to CPython too). The rp2 port has no GIL so the threads run truly concurrently, but this requires very careful synchronisation.
@2dof This solution is only suitable for asyncio and will provide no benefit here. Furthermore, asyncio can only use a single core.
@2dof In this case, it is entirely because they run on different cores. No built-in data structures are safe for concurrent access for operations like append/remove across cores. |
Beta Was this translation helpful? Give feedback.
-
I wrote this doc on this topic. It is primarily aimed at linking a @jimmo I would welcome your review of this doc. |
Beta Was this translation helpful? Give feedback.
-
After accepting that you need some overhead to protect your list from concurrent access (no GIL as discussed above) it might be helpful to see that making a thread-safe list is not too hard:
This way you might keep your code. Also the overhead should not be too heavy, although I didn't benchmark it. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
If I have core 0 checking for a value in a array and core 1 appending entry value into the array is it possible to read partial data?
So far this test script has not crashed...
Beta Was this translation helpful? Give feedback.
All reactions