Kill growing thread after n seconds

I am looking for a better way to solve the following problem (C ++). I have a function defined by some structure that returns an object. Sometimes it takes only milliseconds, but in some cases it takes a few minutes. So I want to stop execution if it takes more time than saying 2 seconds. I was thinking of doing this with streaming streams. An important side value, if the function returns faster than 2 seconds, the program should not wait. So, I was thinking about 2 threads:

1.thread: execute function a       
2.thread: run timer                
if(thread 2 exited bevore thread 1) kill thread 1 
else do nothing

I'm struggling a bit with practical implementation. Special,

  • How to return an object from boost child stream to main stream?
  • How can I kill a stream in boost?
  • My idea is even good, is there a better way to solve the problem in C ++ (with or without raising)?
+3
source share
3 answers

As for the wait, just use thread::timed_join()inside the main thread, this will return falseif the thread has not completed within the set time.

Killing a thread is not possible if your third-party library is not aware of boost: threads. In addition, you almost certainly do not want to “kill” the stream without giving the function the ability to clean up.

I would suggest that you wait, say, 2 seconds, and then continue with some kind of error message, allowing the framework function to complete its work and simply ignore the result if it arrives too late.

Regarding the return value, I would suggest something like

struct myfunction {
   MyObj returnValue;
   void operator() () { 
     // ... 
     returnValue = theComputedReturnValue;
   }
};

// ...
myfunction f;
boost::thread t = boost::thread(boost::ref(f));
t.join(); // or t.timed_join()...
use(f.returnValue); 
// ...
+2
source

- , ( ). , "" ( ( ) ..) / . . .

0

, , " " - !:) , , , , . ( , ), / .. , , - , _(). , (), 2 , interruption_point() 1 .

Threads are in the same process space, so you can have a common state between several threads if there is synchronized access to this common state.

EDIT: just noticed that the OP has already reviewed this ... will leave an answer anyway, I think ...

0
source

Source: https://habr.com/ru/post/1771655/


All Articles