dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Windows main loop and a server loop on 2 threads

  1. #1
    Join Date
    Dec 2017
    Posts
    38

    Windows main loop and a server loop on 2 threads

    I'm trying to setup mongoos server in a Winndows app.
    The server code needs to be in an infinite loop, so does the windows main loop. I put the server code and win loop on 2 threads, the problem is, the program hangs when executed.
    Is there a way to make this work




    Main Windows loop

    Code:
    	int mainLoop(MSG &messages) {
    		while (GetMessage(&messages, NULL, 0, 0))
    		{
    			TranslateMessage(&messages);
    			DispatchMessage(&messages);
    		}
    
    
    		return 1;
    	}

    Server loop

    Code:
    	int serverLoop() {
    
    		struct mg_mgr mgr;
    		struct mg_connection *c;
    		static const char *s_http_port = "80";
    
    		mg_mgr_init(&mgr, NULL);
    		c = mg_bind(&mgr, s_http_port, ev_handler);
    		mg_set_protocol_http_websocket(c);
    
    		for (;;) {
    			mg_mgr_poll(&mgr, 1000);
    		}
    		mg_mgr_free(&mgr);
    
    		return 0;
    	}

    Main

    Code:
    int WINAPI WinMain(HINSTANCE hThisInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow){
    
     // ...
     
    	thread first(mainLoop,messages);   
    	thread second(serverLoop);
    
    	first.join();               
    	second.join();

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,258

    Re: Windows main loop and a server loop on 2 threads

    [moved from Visual C++ Forum]
    Victor Nijegorodov

  3. #3
    Join Date
    Aug 2018
    Location
    Burbank, California
    Posts
    5

    Re: Windows main loop and a server loop on 2 threads

    Consider using PeekMessage() and in your ev_handler function communicate with the GUI thread.

  4. #4
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,119

    Re: Windows main loop and a server loop on 2 threads

    I think it's best to have your main message loop on the main thread, and just have a worker thread to have your serverLoop.
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  5. #5
    Join Date
    Sep 2018
    Posts
    10

    Re: Windows main loop and a server loop on 2 threads

    You should use PeekMessage().

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)