Thread safety

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)

Any advice would be much help.

Thanks.
Consider using a condition variable for this; the general case would be in conjunction with a queue: the reader thread pushes the processed data into the queue and the consumer thread pulls the processed data from it.
See: https://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

For a simpler scenario where no queue is required, there is an example in cppreference.com:
http://en.cppreference.com/w/cpp/thread/condition_variable


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.


Last edited on
> 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.

More information: http://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races


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.

You do have to be careful how you do it.
Last edited on
> 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.
Topic archived. No new replies allowed.