lundi 16 janvier 2023

Multithreaded server - design approach

I have a systemd service which acts as a server for incoming requests (API endpoint). Additionally, this service should monitor the state of the system (cpu load, ram, etc.), this is done by reading in the appropriate files in the /proc filesystem. I plan to update these values each second by spawning a dedicated thread, which will continuously read in the new values.

To my understanding a thread pool would be the wrong pattern to apply here, since these threads (probably around 4 in total) are long running (start and termination depends on the lifetime of the service). What would be a proper approach to manage these threads?

In my current implementation I have a dedicated class for each thread with some helper functions:

class Example{
  public:
    Example() {
      t = std::thread{&Example::run, this};
    }

    ~Example() {
      t.join();
    }

    void read();  // read from /proc fs
    void set();   // update values
    void get();  // access to private data member
    void run();  // thread loop, will call read and set each second
    
    std::thread t;

  private:
    int data;  // type int to keep it simple
}

The server then manually starts each thread on startup:

// constructor snippet
// these are member variables
t1 = Example1();
t2 = Example2();
t3 = Example3();
t4 = Example4();

I'm not sure if this is a proper approach to handle multiple, long running threads. Would it be better to create a dedicated class which handles all threads, so that the server would just have to manage this one object? Are there any other patterns for this kind of work?

Also the thread should be the only one updating the corresponding value, but there could be multiple reads happen at the same time, should a mutex be used during the update process?

Aucun commentaire:

Enregistrer un commentaire