Suppose we have a threaded program. We create some resources (i.e. mutexes), spawn threads that do their own initialization, wait for them to finish, then destroy resources.
void run(void)
{
some_resource global_resource;
global_resource.create();
vector<thread> my_threads;
my_threads.reserve(thread_count);
for(int i = 0; i < thread_count; i++)
my_threads.push_back(
thread([&global_resource](int i)
{
another_resource local_resource;
local_resource.create();
// SIGTERM can happen here:
work_with_resources(global_resource, local_resource, i);
local_resource.destroy();
},
i)
);
for(int i = 0; i < thread_count; i++)
my_threads[i].join();
global_resource.destroy();
}
Now suppose that one of the threads, sadly, received SIGTERM during work_with_resources(). That means the local resource of the thread will never be destroyed.
Question 1: What to do to keep track of resources? Is it possible to destroy the killed thread's local resource?
Question 2: Is the thread after being killed still joinable? Will the join() method return immediately? Is join()ing with the killed thread a good practice?
Question 3: Since the killed thread might have used the global resource, it may be left in invalid state. Is there a way to stop all other threads from using the global resource to prevent further damage?
Does the C++ thread library cooperate with signals at all?
First of all SIGTERM behave differently with different version of POSIX library. In 2.6 SIGTERM will forced the thread to exit cleanly. But with 2.4 the thread will be in an indeterminate state.
Now your first question:-
Question 1: What to do to keep track of resources? Is it possible to destroy the killed thread's local resource?
You have no option to track of resources in this case and not possible to reach the thread anymore.
Now your second question:-
Question 2: Is the thread after being killed still joinable? Will the join() method return immediately? Is join()ing with the killed thread a good practice?
Simply no for all your question.
Now your third question:-
Question 3: Since the killed thread might have used the global resource, it may be left in invalid state. Is there a way to stop all other threads from using the global resource to prevent further damage?
You can use pthread conditional variable in this case (pthread_cond_t).