Is it possible to transfer the ownership of a mutex, critical section etc. from the first thread to the second thread without letting any third thread to grab ownership in the meantime? The documentation for critical section prohibits to call LeaveCriticalSection in a thread other than the one who called EnterCriticalSection:
If a thread calls LeaveCriticalSection when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection to wait indefinitely.
But in my scenario I need to exactly release the synchronization object in a different thread than the one who acquired it, so that no other (third) thread can acquire the ownership of the synchronization object in the mean time (from the moment of acquisition by the first thread till the moment of release by the second thread). A solution in C++ threading or WinAPI calls would be suitable for my needs.
No, thread owenership transfer is not supported. Moreover, I firmly believe that any design which depends on lock ownership is flawed and will cause troubles down the road.
However, if ownership transfer is required only for releasing a lock from a thread different from the one receiving it, you have two options:
Undefined behaviour
Releasing a mutex from the thread which doesn't own it is undefined. However, it is possible to code your application with those. The problem you will have is that data synchronization might not happen on non-cache coherent chips if the thread which locked the mutex was running on one CPU, and unlocking happens on another. As a result, the data which was not protected by another synchronization will be 'dirty'. However, if there is no such data - for instance, mutex is trully used in a 'semaphore' fasion and does not protect any data - this might be acceptable.