c – How to execute as much as possible from a block before the process is terminated?

So consider I have 2 functions in a multi-threaded application – each of them can be running concurrently. The first one is doing some important task while the second one is signaling for low memory condition (and so terminating the process).

I want to create something like a mutex where each time there are threads waiting and one of them is doing so at function 1 (doing important work) – to choice this one to acquire the mutex (instead of function 2 which is terminating the process).

The pseudo-code will look something like this:

special_mutex mutex;

function1() { //can be more than one thread at this point
    //do some important work

function2() { //can be more than one thread at this point
    //terminate process

So as long as there is a mutex waiting at function1, function2 mutex won’t be acquired.

What primitives or pseudo-code using them could help me here?

I’m primarily interested in Win32 API implementation but will be happy for any other ones (since they could give me an idea of how to do it there anyway).