Skip to content

Commit

Permalink
- cleaned up some aspects of twistdroache's osx changeset
Browse files Browse the repository at this point in the history
- added -std=gnu11 to the makefile, to make sure the timespec struct gets defined where available.
  • Loading branch information
jtsiomb committed Feb 19, 2017
1 parent 3478a74 commit 6947c40
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
obj = test.o
bin = test

CFLAGS = -pedantic -Wall -g
CFLAGS = -std=gnu99 -pedantic -Wall -g
LDFLAGS = -lpthread

$(bin): $(obj)
Expand Down
21 changes: 12 additions & 9 deletions c11threads.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ Main project site: https://github.com/jtsiomb/c11threads
#include <sys/time.h>

#define ONCE_FLAG_INIT PTHREAD_ONCE_INIT
#define SLEEP_NANOS 5000000 /* 5 ms */

#ifdef __APPLE__
#define _C11THREADS_NO_TIMED_MUTEX
#ifndef PTHREAD_MUTEX_TIMED_NP
/* detect systems which don't support timed mutexes (like macosx currently) */
#define C11THREADS_NO_TIMED_MUTEX
#endif

#ifdef _C11THREADS_NO_TIMED_MUTEX
#ifdef C11THREADS_NO_TIMED_MUTEX
#define PTHREAD_MUTEX_TIMED_NP PTHREAD_MUTEX_NORMAL
#define C11THREADS_TIMEDLOCK_POLL_INTERVAL 5000000 /* 5 ms */
#endif

/* types */
Expand Down Expand Up @@ -163,17 +164,19 @@ static inline int mtx_trylock(mtx_t *mtx)
static inline int mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
{
int res;
#ifdef _C11THREADS_NO_TIMED_MUTEX
#ifdef C11THREADS_NO_TIMED_MUTEX
/* fake a timedlock by polling trylock in a loop and waiting for a bit */
struct timeval now;
struct timespec sleeptime;

sleeptime.tv_sec = 0;
sleeptime.tv_nsec = SLEEP_NANOS;
sleeptime.tv_nsec = C11THREADS_TIMEDLOCK_POLL_INTERVAL;

while ((res = pthread_mutex_trylock(mtx)) == EBUSY) {
while((res = pthread_mutex_trylock(mtx)) == EBUSY) {
gettimeofday(&now, NULL);

if (now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && (now.tv_usec * 1000) >= ts->tv_nsec)) {
if(now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec &&
(now.tv_usec * 1000) >= ts->tv_nsec)) {
return thrd_timedout;
}

Expand Down Expand Up @@ -258,7 +261,7 @@ static inline void call_once(once_flag *flag, void (*func)(void))
pthread_once(flag, func);
}

#if __STDC_VERSION__ < 201112L || defined (_C11THREADS_NO_TIMED_MUTEX)
#if __STDC_VERSION__ < 201112L || defined(C11THREADS_NO_TIMED_MUTEX)
/* TODO take base into account */
static inline int timespec_get(struct timespec *ts, int base)
{
Expand Down

0 comments on commit 6947c40

Please sign in to comment.