I feel the core of this question is not related to the specific language and library I am using, so I am using some pseudo-code. We can assume C as a language and a WinApi COM DLL.
Let's say I am using a dynamically linked external library which exposes some callbacks in response to some events. Say:
function RegisterCallback(ptr *callback);
Which is to be used as:
function OnEvent(type newValue) {
...
}
...
RegisterCallback(&OnEvent)
...
The library tells me that the callback should be non-blocking. Now, suppose that I want to update an internal state in response to this event. This internal state is accessed by other threads and hence is guarded by a mutex. Thus I would like to write:
function OnEvent(type newValue) {
mutexLock();
internalState = newState;
mutexUnlock()
}
Bu this would be a potentially blocking operation. How should I proceed? The only solution I see out of this is to use a different thread to update the state, like:
function OnEvent(type newValue) {
sendChangeStateMessage(newValue)
}
But, again, in order for this call to be non-blocking, this "sending operation" should be buffered (that is, have a queue of messages), since sending (i.e. sharing data) across threads require syncing, and hence locking.
EDIT: Of course if the operation is atomic (as might be for an integer) there is no such problem /EDIT
To wrap it up: how do you transform a blocking code into a non-blocking one?
Thanks
Locking using a mutex is not always a blocking operation.
If the mutex is only used to protect access to that one variable, and if all other threads acquiring that mutex do not do any blocking operations while the mutex is locked, then this is not a blocking operation. A blocking operation is an operation that will block until something happens. In this case, this use of mutex is unlikely to be blocking unless, for instance, you lock the mutex in another thread and wait for a network read.