Home > database >  c how to delete thread once it has been terminated
c how to delete thread once it has been terminated

Time:06-24

I'm working on a project that uses uses a thread to connect to a server. Whenever the login button is pressed, it initialized a thread to log in with the given IP and port provided by the user.

ServerPage.h

class ServerPage {
public:
    static std::thread serverThread;
    
    static void login();
}

ServerPage.cpp

#include "ServerPage.h"

std::thread ServerPage::serverThread;

void ServerPage::login() {
    while (/*server is not connected*/) {
        if (/*button is clicked and thread is not running*/)
        serverThread = std::thread(Client::init, ip, port);
    }
}

This works well until the button is clicked more than once. I'm able to use the Client class to see the status of the server (connected, not connected, or failure) Is there a way to delete or re initialize so that it can be run until the client is connected?

CodePudding user response:

First of all: threads cannot be restarted. There is no such concept in programming. Unless by "restart" you mean "kill and spawn again".

It is not possible to kill a thread in a cross-platform way. For posix (I don't know about other OS) you can use pthreads (instead of std::thread) and send kill signal to it and spawn it again. But this is a ninja way, not necessarily what you should do. However, if you can't modify Client::init method, then there might be no other choice without weakening your requirements.

A better solution is to pass around "cancellation tokens": small objects that you can register cancel handlers on it. Then you implement Client::init to cancel itself whenever cancellation is triggered. Which you trigger on click.

  • Related