Multithreaded Programming Guide

Initializing a Spin Lock

Use the pthread_spin_init(3C) function to allocate resources required to use a spin lock, and initialize the lock to an unlocked state.

pthread_spin_init() Syntax

int  pthread_spin_init(pthread_spinlock_t *lock, int pshared);
#include <pthread.h>

pthread_spinlock_t lock;
int pshared;
int ret;

/* initialize a spin lock */
ret = pthread_spin_init(&lock, pshared); 

The pshared attribute has one of the following values:



Permits a spin lock to be operated on by any thread that has access to the memory where the spin lock is allocated. Operation on the lock is permitted even if the lock is allocated in memory that is shared by multiple processes.



Permits a spin lock to be operated upon only by threads created within the same process as the thread that initialized the spin lock. If threads of differing processes attempt to operate on such a spin lock, the behavior is undefined. The default value of the process-shared attribute is PTHREAD_PROCESS_PRIVATE.

pthread_spin_init() Return Values

Upon successful completion, the pthread_spin_init() function returns 0. Otherwise, one of the following error codes is returned.



The system lacks the necessary resources to initialize another spin lock.



The system has detected an attempt to initialize or destroy a spin lock while the lock is in use (for example, while being used in a pthread_spin_lock() call) by another thread.



The value specified by lock is invalid.