Я предполагаю, что ваш объект ConnectionHandler
где-то уничтожается. Кроме того, вы указали ConnectionHandler :: start
глупо.
Во-первых, ConnectionHandler :: start
должен быть определен следующим образом:
void ConnectionHandler::start(ConnectionHandler * pThis){
pThis->main();
}
Класс C ++ 11 :: std :: thread
отлично способен сохранить тип аргумента функции, поэтому нет необходимости прибегать к void *
.
Во-вторых, добавьте этот код:
void ConnectionHandler::~ConnectionHandler(){
const void * const meptr = this;
this->connectionList_mutex.lock();
::std::cout << "ConnectionHandler being destroyed at " << meptr << ::std::endl;
this->connectionList_mutex.unlock();
}
И измените конструктор следующим образом:
ConnectionHandler::ConnectionHandler(){
const void * const meptr = this;
::std::cout << "ConnectionHandler being created at " << meptr << ::std::endl;
std::thread t(&this->start, this);
t.detach();
}
Это покажет вам, когда объект ConnectionHandler
будет уничтожен. И я предполагаю, что ваш код уничтожает его, пока ваш выделенный поток все еще работает.
The meptr
thing is because operator <<
has an overload for void *
that prints out the pointer value. Printing out the pointer value for this
will allow you to match up calls to the constructor and destructor if you're creating multiple ConnectionHandler
objects.
Edit: Since it turned out I was correct, here is how I would recommend you write the play ConnectionHandler class:
#include
#include
#include <thread>
#include
#include
class ConnectionHandler {
public:
ConnectionHandler();
~ConnectionHandler();
ConnectionHandler(const ConnectionHandler &) = delete;
const ConnectionHandler &operator =(const ConnectionHandler &) = delete;
int addNewSocket();
private:
int main();
static void start(ConnectionHandler * pThis);
::std::mutex connectionList_mutex;
volatile ::std::atomic_bool thread_shutdown;
::std::thread thread;
};
ConnectionHandler::ConnectionHandler()
: thread_shutdown(false), thread(&this->start, this)
{
}
ConnectionHandler::~ConnectionHandler()
{
thread_shutdown.store(true);
thread.join();
}
void ConnectionHandler::start(ConnectionHandler * pThis){
pThis->main();
}
int ConnectionHandler::addNewSocket(){
::std::lock_guard< ::std::mutex> lock(connectionList_mutex);
::std::cout << "test1" << ::std::endl;
return 0;
}
int ConnectionHandler::main(){
while(!thread_shutdown.load()){
::std::lock_guard< ::std::mutex> lock(connectionList_mutex);
::std::cout << "test2" << ::std::endl;
::std::this_thread::sleep_for(::std::chrono::milliseconds(100));
}
return 0;
}