justvg
justvg

Reputation: 56

Simple Client-Server multithreading. Error

I try to write simple Client-Server program with multithreading just for practice. Here is my code.

Client function always finishes.
Server function sometimes finishes, sometimes does not, but it is not important.
"HELLO" every time is not displayed.
I always have a "Debug Error! abort() has been called". What is wrong in my code?

#include <iostream>
#include <thread>
using namespace std;

void Client();
void Server(thread &cl);

int main()
{     
    thread clientThread = thread(Client);
    thread serverThread = thread(Server, std::ref(clientThread));

    clientThread.join();
    serverThread.join();

    cout << "HELLO" << endl;

    return 0;
}

void Client() 
{
    cout << "CLIENT IS HERE" << endl;
    cout << "CLIENT IS HERE" << endl;
    cout << "CLIENT IS HERE" << endl;
}

void Server(thread &cl) 
{
    cl.join();
    cout << "SERVER IS HERE" << endl;
}

Upvotes: 0

Views: 25

Answers (2)

Wyck
Wyck

Reputation: 11760

You can't call join multiple times on the same thread. Your code calls .join on the clientThread twice. Once in main, and once in the Server.

Once you call join on a thread it is no longer joinable. You only need to join once. You could, I suppose, skip a join by writing something like:

if(clientThread.joinable()) clientThread.join();

But all such joins would have to be written like this, inlcuding the one in the Server thread.

if(cl.joinable()) cl.join();

I recommend only joining once though. Think about it: if the server thread joins with the client, then the code in main that joins with the client thread is redundant.

Upvotes: 1

Ricky L.
Ricky L.

Reputation: 256

You're, potentially, concurrently calling join() on the same std::thread object (clientThread). According to here this is undefined behavior.

Upvotes: 2

Related Questions