### __cxchg -- Exchange Character Value with Memory

Format

>     #include <builtin.h>
>     signed char _Builtin __cxchg(volatile signed char *lockptr,
>                                  signed char value);

Language Level: Extension
__cxchg 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).

For OS/2, you can also use OS/2 semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and an OS/2 semaphore for the resource.

For Windows, you can also use Win32 semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and a Win32 semaphore for the resource.

To implement a fast-RAM semaphore, allocate a volatile memory location (for __cxchg, it must be a signed char), 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 __cxchg from the thread to exchange a nonzero value with that memory location. If __cxchg 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 __cxchg again to reset the memory location to 0.

If __cxchg returns a nonzero value, another thread is already using the resource, and the calling thread must wait for access. You could then use the OS/2 and Windows 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: __cxchg 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 __cxchg.
- You cannot parenthesize a call to __cxchg. (Parentheses specify a call to the function's backing code, and __cxchg has none.)

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

Example

/Gm compiler option

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