I have 20 threads that all start by reading from one huge data array. Most of the time the codes run smoothly. However, once in a while, without reproducible pattern, one or two threads will say no data.
I think it may be a race condition among the threads while reading the huge array. I plan to implement sleep routine or atomic lock. But race conditions should not occur while reading from a memory block, right?
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data.
When race conditions occur. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.
To avoid race conditions, any operation on a shared resource – that is, on a resource that can be shared between threads – must be executed atomically. One way to achieve atomicity is by using critical sections — mutually exclusive parts of the program.
A race condition occurs when the timing or order of events affects the correctness of a piece of code. A data race occurs when one thread accesses a mutable object while another thread is writing to it.
TL;DR Is your array 100% eager?
Excerpting from @jnthn's answer to SO question Is it safe, to share an array between threads? and adding my own italic and bold emphasis:
Concurrent operations Variable size array Read-only, non-lazy Safe Read/write or lazy Not safe ...
it is only safe if [arrays] will only be read from during the period they are being shared [and] if they're not lazy (though given array assignment is mostly eager, you're not likely to hit that situation by accident).
Given that the above is both gospel (or the next best thing), and eminently logical, my guess is your array isn't 100% eager. That and/or there's a Raku(do) bug.
Summarizing, your situation is:
EITHER
You need to fix your code
You haven't previously noticed that your array is not 100% eager. You need to address the laziness by eliminating it before the first attempt at reading data that's lazily written.
Try writing @array.elems
(which forces immediate reification of the entire array) before the first attempt at reading. (Or insert an explicit eager
in the right spot.) Does that fix the problem?
OR
There's a bug in Raku(do)
Either core devs just haven't previously noticed and recorded it, or it's been recorded in one of the bug queues and we/I failed to find it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With