Tie the lifetime of the websocket_server to this thread, not the
main thread, so that we have no lifetime related race conditions
with respect to the underlying libwebsocket_context object.
Change-Id: Icb49f5fa21e7cea5fdc7f4f0023a551f40ef8b49
Signed-off-by: Ossama Othman <ossama.othman@intel.com>
#include <glib.h>
#include <iostream>
#include <glib.h>
#include <iostream>
/**
* settingsd program entry point.
/**
* settingsd program entry point.
settings::manager manager(config.settings_dir());
// The websocket server will run in its own thread.
settings::manager manager(config.settings_dir());
// The websocket server will run in its own thread.
- settings::websocket_server server(config, manager);
- server.run();
+ std::thread(
+ [&config, &manager](){
+ // Tie the lifetime of the websocket_server to this thread,
+ // not the main thread, so that we have no lifetime related
+ // race conditions with respect to the underlying
+ // libwebsocket_context object.
+ settings::websocket_server server(config, manager);
+ server.run();
+ }).detach();
// Glib related events, including GDbus related signal handlers,
// will handled in this (main) thread.
// Glib related events, including GDbus related signal handlers,
// will handled in this (main) thread.
#include "../lib/manager.hpp"
#include <stdexcept>
#include "../lib/manager.hpp"
#include <stdexcept>
context_ = libwebsocket_create_context(&info);
if (context_ == nullptr)
context_ = libwebsocket_create_context(&info);
if (context_ == nullptr)
- throw std::runtime_error("Unable to initialize websocket.\n");
+ throw std::runtime_error("Unable to initialize websocket.");
std::cout << "\n" PACKAGE_NAME " listening for requests on port "
<< info.port << ".\n";
std::cout << "\n" PACKAGE_NAME " listening for requests on port "
<< info.port << ".\n";
void
ivi::settings::websocket_server::run()
{
void
ivi::settings::websocket_server::run()
{
- // Run the websocket event loop in its own thread.
- std::thread(
- [](libwebsocket_context * context){
- try {
- // Run the libwebsockets event loop with an infinite timeout.
- // The negative timeout causes the underlying call poll() to
- // block indefinitely until an event occurs.
- constexpr int const timeout = -1;
- while (libwebsocket_service(context, timeout) >= 0) {
- }
-
- std::cerr << "WebSocket event loop ended.\n";
- } catch(std::exception & e) {
- std::cerr << e.what() << std::endl;
- }
- },
- context_).detach();
+ // Run the libwebsockets event loop with an infinite timeout. The
+ // negative timeout causes the underlying call poll() to block
+ // indefinitely until an event occurs.
+ constexpr int const timeout = -1;
+
+ while (libwebsocket_service(context_, timeout) == 0) {
+ }