Skip to content

Instantly share code, notes, and snippets.

@gyakoo
Created August 21, 2015 16:43
Show Gist options
  • Save gyakoo/7af3d1abce1c156f5cb3 to your computer and use it in GitHub Desktop.
Save gyakoo/7af3d1abce1c156f5cb3 to your computer and use it in GitHub Desktop.
Minimal naïve critical-section and some atomic operations multiplatform
#ifdef _MSC_VER
typedef struct flt_critsec
{
CRITICAL_SECTION cs;
}flt_critsec;
flt_critsec* flt_critsec_create()
{
flt_critsec* cs=(flt_critsec*)flt_malloc(sizeof(flt_critsec));
InitializeCriticalSection(&cs->cs);
return cs;
}
void flt_critsec_destroy(flt_critsec* cs)
{
DeleteCriticalSection(&cs->cs);
flt_free(cs);
}
void flt_critsec_enter(flt_critsec* cs)
{
EnterCriticalSection(&cs->cs);
}
void flt_critsec_leave(flt_critsec* cs)
{
LeaveCriticalSection(&cs->cs);
}
long flt_atomic_dec(fltatom32* c)
{
return InterlockedDecrement(c);
}
long flt_atomic_inc(fltatom32* c)
{
return InterlockedIncrement(c);
}
#else // perhaps pthread/gcc builtings to the rescue?
typedef struct flt_critsec
{
pthread_mutex_t mtx;
}flt_critsec;
flt_critsec* flt_critsec_create()
{
flt_critsec* cs;
cs=(flt_critsec*)flt_malloc(sizeof(flt_critsec));
pthread_mutex_init(&cs->mtx, ... );
return cs;
}
void flt_critsec_destroy(flt_critsec* cs)
{
pthread_mutex_destroy(&cs->mtx);
flt_free(cs);
}
void flt_critsec_enter(flt_critsec* cs)
{
pthread_mutex_lock(&cs->mtx);
}
void flt_critsec_leave(flt_critsec* cs)
{
pthread_mutex_unlock(&cs->mtx);
}
long flt_atomic_dec(fltatom32* c)
{
return __sync_sub_and_fetch(c,1);
}
long flt_atomic_inc(fltatom32* c)
{
return __sync_add_and_fetch(c,1);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment