I have a third party library. This library has function named int foo(). Function is thread based and I cannot change the content of the function. (It does not belong to me.)
When I call the function, it becomes locked and does not return the value. Is there any way to kill this thread based function, when the function is locked? For example, when the function doesn't return the value within 5 seconds, I want to kill it without any memory leak.
Since its a third party library which you have no control over, you cannot portably terminate the thread that runs that code, though you can call for the native_handle and use its thread termination facilities, you will most likely introduce leaks.
Note that, threads live in the same Address space, hence a corruption or a leak from one thread affects your entire program.
The option I can think of is to spawn a new process to run that code, if after 5 seconds it doesn't complete, you can request the OS to kill it. {No memory leaks and resources are freed} :-) ...your best choice...
A possible solution, as suggested by StoryTeller, is to call foo() in a different thread, which you control. When timeout happens, you leave the thread running in the background. This means foo() continues execution, but your program can continue. This method is portable, so you don't need to write any operation system dependent code.
Leaving foo() running can have unwanted side effects, and foo() will continue to use resources in the background, so you have to test whether this works in your situation.
#include <boost/thread.hpp>
#include <ctime>
void FooWrapper(bool& hasResult, int& result){
result = foo();
hasResult = true;
}
void AnotherFunction(){
bool hasResult = false;
int result;
boost::thread(&FooWrapper, boost::ref(hasResult), boost::ref(result));
// Wait until result, or until timeout
std::time_t startTime = time(0);
while(!hasResult && time(0) < startTime + 5){
// Do nothing
}
if(!hasResult){
throw "timeout";
}
else{
// Use result
}
}
I am using boost thread here, but you can convert it to use any thread library you want.
No, there is no way to do so without memory leaks, because the thread running foo may allocate heap data, might put some private data inside values owned by your main program or some other thead.
Notice that data liveness (and virtual address space) is a whole-program property: some heap data does not belong to a (particular) thread, but to the whole process. The library could (and probably should) use smart pointers as a convention.