Skip to content

Commit

Permalink
Problem: pthread condvar timeouts are broken (#2967)
Browse files Browse the repository at this point in the history
* fix pthread condvar timeouts

This fixes a race condition / hang for threadsafe sockets.
Context: zeromq/czmq#1873 (comment)
  • Loading branch information
lunixbochs authored and bluca committed Mar 5, 2018
1 parent d54633a commit 3658b2b
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/condition_variable.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,26 @@ class condition_variable_t

#include <pthread.h>

#if defined(__ANDROID_API__) && __ANDROID_API__ < 21
#define ANDROID_LEGACY
extern "C" int pthread_cond_timedwait_monotonic_np (pthread_cond_t *,
pthread_mutex_t *,
const struct timespec *);
#endif

namespace zmq
{
class condition_variable_t
{
public:
inline condition_variable_t ()
{
int rc = pthread_cond_init (&cond, NULL);
pthread_condattr_t attr;
pthread_condattr_init (&attr);
#if !defined(ZMQ_HAVE_OSX) && !defined(ANDROID_LEGACY)
pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
#endif
int rc = pthread_cond_init (&cond, &attr);
posix_assert (rc);
}

Expand All @@ -198,9 +210,9 @@ class condition_variable_t
if (timeout_ != -1) {
struct timespec timeout;

#if defined ZMQ_HAVE_OSX \
&& __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12
alt_clock_gettime (SYSTEM_CLOCK, &timeout);
#ifdef ZMQ_HAVE_OSX
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
#else
clock_gettime (CLOCK_MONOTONIC, &timeout);
#endif
Expand All @@ -212,8 +224,15 @@ class condition_variable_t
timeout.tv_sec++;
timeout.tv_nsec -= 1000000000;
}

#ifdef ZMQ_HAVE_OSX
rc = pthread_cond_timedwait_relative_np (
&cond, mutex_->get_mutex (), &timeout);
#elif defined(ANDROID_LEGACY)
rc = pthread_cond_timedwait_monotonic_np (
&cond, mutex_->get_mutex (), &timeout);
#else
rc = pthread_cond_timedwait (&cond, mutex_->get_mutex (), &timeout);
#endif
} else
rc = pthread_cond_wait (&cond, mutex_->get_mutex ());

Expand Down

0 comments on commit 3658b2b

Please sign in to comment.