-1

Currently I start my threads and wait for it to finish:

void ClassA::StartTest() // btn click from GUI
{
    ClassB classB;

    std::vector<std::thread> threads;
    for(int counter=0; counter<4; counter++)
    {
        threads.at(counter) = std::thread(&ClassB::ExecuteTest, classB);
        // if I join the threads here -> no parallelism
    }

    // wait for threads to finish
    for(auto it=threads.begin(); it!=threads.end(); it++)
        it->join();
}

ClassB

#include <mutex>

ClassB
{
public:
    void ExecuteTest(); // thread function
private:
    std::mutex m_mutex;
    bool ExecuteOtherWork(std::string &value);
};

Relevant method ExecuteTest()

void ClassB::ExecuteTest()
{
    std::string tmp;

    std::lock_guard<std::mutex> lock(m_mutex); // lock mutex
    std::stringstream stream(pathToFile);

    while(getline(stream, tmp, ',')) // read some comma sep stuff 
    {
        if(!ExecuteOtherWork(tmp)) break;
    }
}

All ok, but I want to have a thread timeout: lets say after 40sec the threads have to quit there work and return to main thread. How can I do that?

Thx!

leon22
  • 5,280
  • 19
  • 62
  • 100
  • Getline and its streaming ilk don't take well to time-outs, and killing the thread will leave that mutex locked. Any way you could write a terminate message into the stream? – user4581301 May 20 '15 at 07:28

1 Answers1

0

In the while loop add a check for the timeout:

std::chrono::time_point<std::chrono::steady_clock> start(std::chrono::steady_clock::now());
std::chrono::seconds timeout(timeoutinSec);
while(getline(stream, tmp, ',') && std::chrono::steady_clock::now() - start < timeout) // read some comma sep stuff 
{
    if(!ExecuteOtherWork(tmp)) break;
}

If ExecuteOtherWork() is a quick operation then you could check the time every X times the loop is executed.

Paolo Brandoli
  • 4,681
  • 26
  • 38
  • Not a bad solution, but it won't kick out from a blocked getline call. – user4581301 May 20 '15 at 07:27
  • Maybe one should move the blocking getline call to a seperate thread. The "timing" thread should not block. Unless getline provides the API to only block for a certain period, another solution should be found. I'm not aware of how one can unblock a thread waiting on console in std manner, but this thread has something http://stackoverflow.com/questions/27710672/c-console-input-blocks-so-i-cant-kill-thread – Werner Erasmus May 20 '15 at 07:52
  • Thx! In ExecuteOtherWork() I communicate with hardware -> so if the device hang or crash I have no chance to exit the thread? – leon22 May 20 '15 at 10:50