Example
This is an example of a swap
function that fails to be reentrant (as well as failing to be thread-safe). As such, it should not have been used in the interrupt service routine isr
:
swap
could be made thread-safe by making t
thread-local. It still fails to be reentrant, and this will continue to cause problems if isr
is called in the same context as a thread already executing swap
.
The following (somewhat contrived) modification of the swap function, which is careful to leave the global data in a consistent state at the time it exits, is perfectly reentrant; however, it is not thread-safe since it does not ensure the global data is in a consistent state during execution:
int t; void swap(int *x, int *y) { int s; s = t; // save global variable t = *x; *x = *y; // hardware interrupt might invoke isr here! *y = t; t = s; // restore global variable } void isr { int x = 1, y = 2; swap(&x, &y); }Read more about this topic: Reentrancy (computing)
Famous quotes containing the word example:
“Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.”
—Marcel Proust (18711922)