Hi i'm new to programming and trying out some multithreading scenarios.
I'm creating 2 threads , one which reads file data and processes it into a struct.
The other thread loop reads the struct and displays the data on the UI.
Would I need some sort of mutex/locks on the read/write?
.. or would a 'dirty' pointer suffice? (by having the writer thread uses a new/backup struct to write to then publishes it to the reader by updating the pointer)
you should not have to lock. Mutex & locks are used when 2 threads need to potentially modify the same thing, for most scenarios.
All you need here is for thread 1 to finish processing 1 struct before thread 2 consumes it.
You may not even need any thread mechanics at all..
consider..
thread a
{
read to local x
read to local y
...
add new complete item to shared container
}
thread b
{
while not done
if shared container.size() > last checked size
process next item
update last checked size
}
so in theory every time you finish a full read and load it into your container, the other thread will see it and process it, then go back to sleep until another one appears...
No race conditions this way. How you handle the "done" bit depends on whether it can read forever (stream?) vs a fixed file etc.
> Mutex & locks are used when 2 threads need to potentially modify the same thing
Even if only one thread modifies 'the same thing' and another thread concurrently accesses 'the same thing' there is a data race.
Like with the 'shared container' in the example that follows.
Or the writer of the 'shared container' being used must have done what ever it takes to make it thread-safe.
correct, I should have said when one of them modifies, not both.
If the container updates the size last, it should be fine. At the point the 2nd thread reads the updated value for size, the data is there safely. If it reads the old value for size while the container is mid-update, it does nothing.
> If the container updates the size last, it should be fine.
When it updates the size (when ever that is), if another thread tries to concurrently read the size, there is undefined behaviour. Unless the designer of the container has taken steps to protect against this.