Maxx
Maxx

Reputation: 185

With C++ concurrency, do I need to use mutual exclusion?

I have to design an app that reads UDP data off the local net and stores the data in a Current Value Table (CVT).

Then, a separate thread will come along and read the values out of the CVT, massage them, and send them out over UDP. CVT entries will consist of individual scalars like floats and ints.

My question is, how much mutual exclusion do I need to protect updating/reading from the CVT?

Put another way, if I have a thread writing to an 32bit int and another thread reading from that int, do I need to employ a mutex for it?

I don't care if the reader thread doesn't get the absolute latest value stored, I'm just concerned about trying to read that location WHILE it is being changed. I know the keyword "volatile" has uses for this scenario in Java, but it doesn't do the same thing in C++.

Upvotes: 1

Views: 255

Answers (4)

Desmond Hume
Desmond Hume

Reputation: 8607

As long as your 32 bit int is properly aligned in memory, and I'm guessing that it is because it's by default on most modern platforms, reading that int is practically thread-safe.

Upvotes: 0

marko
marko

Reputation: 9159

As you describe this problem, it is already threadsafe provided you have only one writer (assuming the code runs on a 32-bit or higher word-width processor - in which case the 32-bit write is atomic).

The volatile storage modifier tells the compiler that a variable has non-standard load-store semantics - namely that it can't rely on a copy in CPU register remaining consistent with the value in memory.
The general side effect is to disable any optimizations around that variable (ie. ones that rely on the storage in memory not changing beneath it). The result is a reload from memory on each use.

This is one of the few occasions where volatile is of use in a multi-threading situation.

Upvotes: 1

Coffee
Coffee

Reputation: 9

It depends what you are using for your current value table. If you're using a database like SQLServer, then you shouldn't have any worries because the database will handle it.

If you're using the file system, then your problem remains.

You could write a TCP based Client/Server that queues requests and responds to them in sequential order.

If you're using memory then you'll need to use a mutex.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490178

A lot here depends on what sort of platform you're using to support the threading. If you have atomic types available, you can just use those. Otherwise, yes, you're pretty much stuck with a mutex (of some sort -- many platforms have more than one type).

Upvotes: 3

Related Questions