How to prevent that multiple Threads access the same Hardware Button using Mutex?

  c++, mutex, object, real-time, stdthread

I have some hardware Buttons which I want to control via c++ code.
The application is going to be used for testing of an hardware System.

The whole code is time sensitive.
A single button can be used via: func_SingleButtonInput(int); (-> Shown below)
That function works great if its used in a single Thread.

Problems occur if I want to simulate more activated Buttons at once, for example with multiple Threads running the same function simultaneously.
The aim is to simulate a person that pushes multiple Buttons at once for different periods of time (random()). The whole testing procedure should run days (or weeks), if an collision is possible, it will happen.

Question:

-> How to prevent that multiple Threads access the same button?

This seems to be an use case for std::mutex. But how to link a Mutex to a Button?
The amount of Buttons is defined as NUMBER_BUTTONS. The amount may be changed in the future (By other developers).
To my knowledge a class Button doesn’t solve that problem. Mutex is not copyable. So if one Object is created for every hardware Button than working with Mutex does not work.

//Call with: std::thread thread_Name(func_SingleButtonInput, TEST_DURATION_SECONDS);

void func_SingleButtonInput(int seconds_duration) {
    auto timeOfStart = std::chrono::system_clock::now(); //Time of start to calculate duration
    std::chrono::duration<double> diff;                  //Calculate duration of Thread already running
    RelayControl rControl;                               //Controls Hardware Buttons
    
    do {
        int timeButtonPressed = random(MS_TIMEBUTTONPRESSED_MIN, MS_TIMEBUTTONPRESSED_MAX);
        int wait = random(timeButtonPressed + 10, MS_WAITING_MAX);       //Allows only one Button at once
        int charID = randomChar(NUMBER_BUTTONS);
        rControl.setRelayForMilliSeconds((char)charID, timeButtonPressed);
        
        usleep(wait * 1000);

        //Ending of loop -> Check if certain amount of seconds have passed
        auto currentTime = std::chrono::system_clock::now();
        diff = currentTime - timeOfStart;
    } while ((int) diff.count() < seconds_duration);
}

Source: Windows Questions C++

LEAVE A COMMENT