Omi
Omi

Reputation: 1148

Multi-threading work around query

I have an app which has a main thread that talks to a remote server over tcp and obtains some data. Before establishing a tcp connection, the main thread spawns a new thread that among other things prints the data obtained by the main thread.

Here's some pseudo-code on how the parallel thread does that -

while (1)
{
    if(dataObtained)
    {
        printDataFromMainThread(remoteData);
        exit;
    }
}

In main thread:

recvOverTCPSocket();
saveData(remoteData);
dataObtained = true;

I was initially concerned that this is not thread-safe and when we run this app, there are seemingly no issues. I still have my concerns though.

It is clear that the parallel thread will read data only when the dataObtained flag is true...which happens only after all the data is saved. this ensures there is no chance of the parallel thread reading data while it is still being updated by the main thread.

However, I still am not sure if this is the right approach and whether I am missing any scenario where this is likely to fail.

Any inputs/comments. Does the above code snippet help us avoid using a semaphore while updating the data?

Upvotes: 0

Views: 82

Answers (2)

Jeremy Friesner
Jeremy Friesner

Reputation: 73091

From your code, it looks like your parallel thread never blocks; that means that while your program is running, your parallel thread will probably be using up all of the available CPU cycles on one of the computer's cores. That's generally something you want to avoid, as it's very inefficient (e.g. it will tend to slow down other programs that are running on the computer, and on battery-powered devices it will unnecessarily deplete the battery).

You can avoid that e.g. by having the parallel thread block on a condition variable which the main thread would signal when the data is ready... but then the question becomes, why are you using multiple threads at all? It doesn't appear that your program is getting any benefit from having two threads, since only one of them is doing useful work at any given time anyway. Why not just have the same thread do both the TCP data download and then the printing of the downloaded data? That would give you the sequential behavior you are looking for, and be much simpler, more efficient, and less error-prone.

Upvotes: 1

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

I would make boolean flag an atomic, but otherwise it should work

std::atomic<bool> dataObtained(false);

...

// in working thread
while (!dataObtained) { std::this_thread::yield(); }
// receive and print data

Upvotes: 0

Related Questions