72 lines
1.5 KiB
C
72 lines
1.5 KiB
C
// https://www.cs.utexas.edu/~pingali/CS378/2015sp/lectures/Spinlocks%20and%20Read-Write%20Locks.htm
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <stddef.h>
|
|
#include <pthread.h>
|
|
|
|
#if 0 /* use gcc builtin function */
|
|
struct stm_spinlock
|
|
{
|
|
long value;
|
|
};
|
|
|
|
struct stm_spinlock *stm_spinlock_new(void)
|
|
{
|
|
struct stm_spinlock *splock = (struct stm_spinlock *)calloc(1, sizeof(struct stm_spinlock));
|
|
return splock;
|
|
}
|
|
|
|
void stm_spinlock_lock(struct stm_spinlock *splock)
|
|
{
|
|
while (__sync_lock_test_and_set(&splock->value, 1))
|
|
{
|
|
}
|
|
}
|
|
|
|
void stm_spinlock_unlock(struct stm_spinlock *splock)
|
|
{
|
|
__sync_lock_release(&splock->value);
|
|
}
|
|
|
|
void stm_spinlock_free(struct stm_spinlock *splock)
|
|
{
|
|
if (splock)
|
|
{
|
|
free(splock);
|
|
}
|
|
}
|
|
#else /* pthread spin lock */
|
|
struct stm_spinlock
|
|
{
|
|
pthread_spinlock_t lock_ins;
|
|
};
|
|
|
|
struct stm_spinlock *stm_spinlock_new(void)
|
|
{
|
|
struct stm_spinlock *splock = (struct stm_spinlock *)calloc(1, sizeof(struct stm_spinlock));
|
|
pthread_spin_init(&splock->lock_ins, PTHREAD_PROCESS_PRIVATE);
|
|
return splock;
|
|
}
|
|
|
|
void stm_spinlock_lock(struct stm_spinlock *splock)
|
|
{
|
|
pthread_spin_lock(&splock->lock_ins);
|
|
}
|
|
|
|
void stm_spinlock_unlock(struct stm_spinlock *splock)
|
|
{
|
|
pthread_spin_unlock(&splock->lock_ins);
|
|
}
|
|
|
|
void stm_spinlock_free(struct stm_spinlock *splock)
|
|
{
|
|
if (splock)
|
|
{
|
|
pthread_spin_destroy(&splock->lock_ins);
|
|
free(splock);
|
|
}
|
|
}
|
|
#endif |