|PTHREAD_SPIN_INIT(3)||Linux Programmer's Manual||PTHREAD_SPIN_INIT(3)|
int pthread_spin_init(pthread_spinlock_t *lock, int pshared); int pthread_spin_destroy(pthread_spinlock_t *lock);
Compile and link with -pthread.
_POSIX_C_SOURCE >= 200112L
The pthread_spin_init() function allocates any resources required for the use of the spin lock referred to by lock and initializes the lock to be in the unlocked state. The pshared argument must have one of the following values:
- The spin lock is to be operated on only by threads in the same process as the thread that calls pthread_spin_init(). (Attempting to share the spin lock between processes results in undefined behavior.)
- The spin lock may be operated on by any thread in any process that has access to the memory containing the lock (i.e., the lock may be in a shared memory object that is shared among multiple processes).
Calling pthread_spin_init() on a spin lock that has already been initialized results in undefined behavior.
The pthread_spin_destroy() function destroys a previously initialized spin lock, freeing any resources that were allocated for that lock. Destroying a spin lock that has not been previously been initialized or destroying a spin lock while another thread holds the lock results in undefined behavior.
Once a spin lock has been destroyed, performing any operation on the lock other than once more initializing it with pthread_spin_init() results in undefined behavior.
- The system has insufficient resources to initialize a new spin lock.
- Insufficient memory to initialize the spin lock.
Support for process-shared spin locks is a POSIX option. The option is supported in the glibc implementation.
If threads create a deadlock situation while employing spin locks, those threads will spin forever consuming CPU time.
User-space spin locks are not applicable as a general locking solution. They are, by definition, prone to priority inversion and unbounded spin times. A programmer using spin locks must be exceptionally careful not only in the code, but also in terms of system configuration, thread placement, and priority assignment.