简体   繁体   中英

How to run multiple objects of a class having a function calling only threads in C++?

I have a subclass called WiFiControlImplementation , it is a subclass of another class called WifiSniffer

The WiFiControlImplementation contains a public method:

class WiFiControlImplementation : public WifiSniffer {
    public:
       WiFiControlImplementation(){};
       void startControlProcess (void);
    private:
       bool callback            (void) override;

and it inherits two functions from WifiSniffer:

class WifiSniffer{
    public:
       WifiSniffer(){};
       void  run                (void);
       void  runChannelHop      (int hopscale);
    private:
       virtual bool callback         (void);

The function startControlProcess must run the two inherited functions in separate threads:

void WiFiControlImplementation::startControlProcess(){
   std::thread channelhop  (&WiFiControlImplementation::runChannelHop,this,3);
   std::thread runner      (&WiFiControlImplementation::run,this);
}

Now how to do if I want to run the object in another main file (example: main.cpp)? Do I do this:

   #include "wifi_ControlImplementation.h"
   int main(int argc, char **argv){
      WiFiControlImplementation job;
      job.startControlProcess();
      while(1){}; // For not stopping the main thread so that the object thread can still run ?
   }

And how should I do it if I want to run multiple objects of the same class like this:

   #include "wifi_ControlImplementation.h"
   int main(int argc, char **argv){
      WiFiControlImplementation job;
      job.startControlProcess();

      WiFiControlImplementation job2;
      job2.startControlProcess();

      WiFiControlImplementation job3;
      job3.startControlProcess();
      while(1){};
   }

In order to run class functions in threads from a main program, I just used a function for each one of them, and the second function returns a thread that executes the first function in a lambda call, here is the example:

  • In wifi_Hopper.h :
#include <thread>
class wifi_Hopper {
     public:
        wifi_Hopper(){};
        std::thread start_thread(void) {
            return std::thread( [=] { start_hopping(); } );
        }
     private:
        void start_hopping(void);
}
  • In main.cpp :
#include "wifi_Hopper.h"
int main(int argc, char **argv){
   wifi_Hopper wH;
   std::thread HopperThread = wH.start_thread();
   HopperThread.join();
   return 0;
}
  • And you can define many functions in one class and make a thread-return function for each one, and you can call all of them with the same object of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM