I try to implement following logic (a kind of pseudo-code) using pthread
:
pthread_mutex_t mutex;
threadA()
{
lock(mutex);
// do work
timed_lock(mutex, current_abs_time + 1 minute);
}
threadB()
{
// do work in more than 1 minute
unlock(mutex);
}
I do expect threadA
to do the work and wait untill threadB
signals but not longer than 1 minute. I have done similar a lot of time in Win32 but stuck with pthreads: a timed_lock
part returns imediately (not in 1 minute) with code ETIMEDOUT
.
Is there a simple way to implement the logic above?
even following code returns ETIMEDOUT
immediately
pthread_mutex_t m;
// Thread A
pthread_mutex_init(&m, 0);
pthread_mutex_lock(&m);
// Thread B
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
struct timespec time = {now.tv_sec + 5, now.tv_nsec};
pthread_mutex_timedlock(&m, &time); // immediately return ETIMEDOUT
Does anyone know why? I have also tried with gettimeofday
function
Thanks
I implemented my logic with conditional variables with respect to other rules (using wrapping mutex, bool flag etc.) Thank you all for comments.