'asio::thread created in object with global scope causes strange behavior, but not if it is created in main

I have been battling a problem for a day or so and "solved" it but I wonder if anyone knows why it must be so, or whether I have just hacked my way around a deeper problem in my code. Using the asio library I cerated a communication object called amjCom. Here is the constructor in which it calls asio::thread (I am using asio, not boost::asio).

amjCom::amjCom(std::function<void(Handle,Handle)> session_callback,
                 std::function<void(Handle,Packet)> receive_callback,
                 std::function<void(Handle)> disconnect_callback):
  _id(0),_session_callback(session_callback),_receive_callback(receive_callback),
  _disconnect_callback(disconnect_callback){
  
  asio::thread t([=]{std::cout << "amjCom thread start" << std::endl;
      asio::executor_work_guard<decltype(_io_context.get_executor())>
    work{_io_context.get_executor()};
      _io_context.run();
      std::cout << "thread end" << std::endl;});
}

You can see callback functions for when new connections are created by servers in the object, for when packets arrive, and for when a connection is disconnected, but that is not part of my question.

Here is the strange thing which I would like feedback on. If I create an object of type amjCom at global scope like this:

amjCom c(&session,&receive,&disconnect);
int main(int argc, char *argv[]){

i get lots of strange behavior in the code. However if I move the above line just inside of main, like this:

int main(int argc, char *argv[]){
  amjCom c(&session,&receive,&disconnect);

Everything works as expected (so far). Of course I then have to pass around references to c.

Does anyone have any idea of why creating my object at global scope causes problems? I assume it has something to do with the creation of a thread, but I don't understand it. I assume the thread will be created in this case before main is called and perhaps that is an issue? Of course it could also just be a strange bug deep in my code.

Thank you for all feedback.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source