Question: 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.

Answer: 
A possible solution, as suggested by [StoryTeller](https://stackoverflow.com/users/817643/storyteller "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](https://en.wikipedia.org/wiki/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*.