vsync / spinlock / rec_spinlock.h
Recursive spinlock implementation using recursive.h.
Groups: Reentrant
see caslock.h
Example:
#include <vsync/spinlock/rec_spinlock.h>
#include <vsync/common/assert.h>
#include <pthread.h>
#include <stdio.h>
#define N 12
#define EXPECTED_VAL N
rec_spinlock_t g_lock = REC_SPINLOCK_INIT();
vuint32_t g_x = 0;
vuint32_t g_y = 0;
void *
run(void *args)
{
vuint32_t tid = (vuint32_t)(vsize_t)args;
// can be acquired multiple times without causing dead-lock
rec_spinlock_acquire(&g_lock, tid);
rec_spinlock_acquire(&g_lock, tid);
g_x++;
g_y++;
rec_spinlock_release(&g_lock);
rec_spinlock_release(&g_lock);
(void)args;
return NULL;
}
int
main(void)
{
pthread_t threads[N];
for (vsize_t i = 0; i < N; i++) {
pthread_create(&threads[i], NULL, run, (void *)i);
}
for (vsize_t i = 0; i < N; i++) {
pthread_join(threads[i], NULL);
}
ASSERT(g_x == EXPECTED_VAL);
ASSERT(g_x == g_y);
printf("Final value %u\n", g_x);
return 0;
}
Macros
| Macro | Description |
|---|---|
| REC_SPINLOCK_INIT | Initializer of rec_spinlock. |
Macro REC_SPINLOCK_INIT
REC_SPINLOCK_INIT()
Initializer of rec_spinlock.
Functions
| Function | Description |
|---|---|
| rec_spinlock_init | Initializes the recursive spinlock. |
| rec_spinlock_tryacquire | Tries to acquire the recursive spinlock. |
| rec_spinlock_acquire | Acquires the recursive spinlock. |
| rec_spinlock_release | Releases the recursive spinlock. |
Function rec_spinlock_init
static void rec_spinlock_init(struct rec_spinlock_s *l)
Initializes the recursive spinlock.
Parameters:
l: address of rec_spinlock_t object.
Note: alternatively use
REC_SPINLOCK_INIT.
Function rec_spinlock_tryacquire
static vbool_t rec_spinlock_tryacquire(struct rec_spinlock_s *l, vuint32_t id)
Tries to acquire the recursive spinlock.
Parameters:
l: address of rec_spinlock_t object.id: thread ID or core ID.
Returns: true, if lock is acquired successfully.
Returns: false, if failed to acquire the lock.
Function rec_spinlock_acquire
static void rec_spinlock_acquire(struct rec_spinlock_s *l, vuint32_t id)
Acquires the recursive spinlock.
Parameters:
l: address of recursive spinlock lock objectid: thread ID or core ID.
Function rec_spinlock_release
static void rec_spinlock_release(struct rec_spinlock_s *l)
Releases the recursive spinlock.
Parameters:
l: address of rec_spinlock_t object.