chenzhongpu
chenzhongpu

Reputation: 6871

C++ thread: how to send message to other long-live thread?

I have a server listening to some port, and I create several detached threads.

Not only the server it self will run forever, but also the detached threads will run forever.

//pseudocode
void t1_func()
{
   for(;;)
   {
     if(notified from server)
         dosomething();
   }
}
thread t1(t1_func);
thread t2(...);
for(;;)
{
  // read from accepted socket
  string msg = socket.read_some(...);
  //notify thread 1 and thread 2;
}

Since I am new to multithreading, I don't know how to implement such nofity in server, and check the nofity in detached threads.

Any helpful tips will be appreciated.

Upvotes: 1

Views: 2742

Answers (1)

phantom
phantom

Reputation: 3342

The easiest way to do this is with std::condition_variable. std::condition_variable will wait until another thread calls either notify_one or notify_all on it and only then will it wake up.

Here is your t1_func implemented using condition variables:

std::condition_variable t1_cond;
void t1_func()
{
    //wait requires a std::unique_lock
    std::mutex mtx;
    std::unique_lock<std::mutex> lock{ mtx };
    while(true)
    {
        t1_cond.wait(lock);
        doSomething();
    }
}

The wait method takes a std::unique_lock but the lock doesn't have to be shared to notify the thread. When you want to wake up the worker thread from the main thread you would call notify_one or notify_all like this:

t1_cond.notify_one();

If you want to have the thread wake up after a certain amount of time you could use wait_for instead of wait.

Upvotes: 1

Related Questions