### __lxchg -- Exchange Integer Value with Memory

Format

>     #include <builtin.h>
>     int _Builtin __lxchg(volatile int*lockptr, int value);

Language Level: Extension
__lxchg puts the specified value in the memory location pointed to by lockptr, and returns the value that was previously in that location.

Use this function to implement fast-RAM semaphores to serialize access to a critical resource (so that only one thread can use it at a time). You can also use system semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and a system semaphore for the resource.

To implement a fast-RAM semaphore, allocate a volatile memory location lockptr (for __lxchg, it must be of type int), and statically initialize it to 0 to indicate that the resource is free (not being used). To give a thread access to the resource, call __lxchg from the thread to exchange a non-zero value with that memory location. If __lxchg returns 0, the thread can access the resource; it has also set the memory location so that other threads can tell the resource is in use. When your thread no longer needs the resource, call __lxchg again to reset the memory location to 0.

If __lxchg returns a non-zero value, another thread is already using the resource, and the calling thread must wait for access using a semaphore. You could then use the semaphore to inform your waiting thread when the resource is unlocked by the thread currently using it.

It is important that you set the memory to a nonzero value when you are using the resource. You can use the same nonzero value for all threads, or a unique value for each.

Note: __lxchg is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:

- You cannot take the address of __lxchg.
- You cannot parenthesize a call to __lxchg. (Parentheses specify a call to the function's backing code, and __lxchg has none.)

Return Value
__lxchg returns the previous value stored in the memory location pointed to by lockptr.

Example

__cxchg -- Exchange Character Value with Memory
__sxchg -- Exchange Integer Value with Memory
<builtin.h>