0

I have a thread with a socket waiting for a message, but there is also another thread created from the previous one to terminate the first thread in case of not receiving a message in less than 5 seconds. How can I finish the first thread from the second?

// the second thread
void b(int t)
{
    std::chrono::steady_clock::time_point currentTime = 
    std::chrono::high_resolution_clock::now();
    while (1)
    {
        std::chrono::steady_clock::time_point n = std::chrono::high_resolution_clock::now();
        int a = std::chrono::duration_cast<std::chrono::milliseconds>(n - currentTime).count();
        if (a >= t)
        {
            std::cout << "time out" << std::endl;
            break;
        }
    }
}

// the first thread
void a(Sock s)
{
    std::thread(&b);
    const char *msg[5000];
    s.Read(msg[0], sizeof(msg));
    std::cout << *msg << std::endl;
    s.Send("MRS");
    s.Close();
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    For example you can use something like a "Stop" flag, check this [post](https://stackoverflow.com/questions/36872859/terminate-a-thread-from-outside-in-c11) – qloq Jun 28 '21 at 11:55
  • *but there is also another thread created from the previous one to terminate the first thread in case of not receiving a message in less than 5 seconds. How can I finish the first thread from the second* Using a separate thread to implement a timout?!?! [`man select`](https://man7.org/linux/man-pages/man2/select.2.html) – Andrew Henle Jun 28 '21 at 11:58
  • 1
    Is the `Sock` class coming from a library? If so, could you point us to it? There may be high-level support for what you need provided in there. –  Jun 28 '21 at 12:40

0 Answers0