The answer is specific to the OS because C++ doesn't abstract thread termination.
Note that functions can only be killed mid-flight by an interrupt mechanism. After the thread is marked for deletion by TerminateThread
, after some number of microseconds (controlled by NT interrupt latency commands) the OS will acquire control of the CPU executing the thread. It may actually be difficult to get this down to 500 microseconds, furthermore, the latency will vary system to system. See DPC latency and tools like DPC Latency Checker.
Also I suspect something terrible will happen to the IO handles, meaning subsequent commands to them might result in a fault.
#include <thread>
#include <iostream>
#include <windows.h>
int main(int argc, char *argv[])
{
auto thread_to_run_the_command_on = std::thread( [] {
std::cout << "Started" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));// Your function goes here
std::cout << "Never Called" << std::endl;
// thread floats away into the aether, also RAII is violated for objects in this scope
});
//give it some time to start
std::this_thread::sleep_for(std::chrono::seconds(3));
const auto windows_native_thread_handle = thread_to_run_the_command_on.native_handle();
TerminateThread(windows_native_thread_handle, 0);
thread_to_run_the_command_on.detach();
}