Reputation: 7061
I am trying to use pthread_mutex_timedlock
function from pthreads
in my 32 bit assembly language program. The code looks following way:
struct timespec
.tv_sec dd ? ; time in seconds
.tv_nsec dd ? ; time is nano seconds
ends
;....
.time timespec ; the timespec structure
;....
; the code where pthread_mutex_timedlock is used
mov eax, [.timeout] ; the timeout in [ms]
mov ecx, 1000
cdq
div ecx ; the timeout in eax [s]
imul edx, 1000000 ; the remainder in edx [ns]
mov [.time.tv_sec], eax
mov [.time.tv_nsec], edx
lea eax, [.time]
cinvoke pthread_mutex_timedlock, [.ptrMutex], eax
test eax, eax
jnz .error
The problem is that the pthread_mutex_timedlock
function locks the mutex only if it is immediately unlocked.
If the mutex is locked in this moment, the function pthread_mutex_timedlock
returns immediately with ETIMEDOUT
error, without waiting for timeout, ignoring the values set in the timespec
structure.
What I am doing wrong?
Upvotes: 2
Views: 419
Reputation: 239261
The timeout for pthread_mutex_timedlock()
is an absolute timeout, not relative - it's returning immediately because the absolute time represented by your timeout value has passed long ago.
If you want a "timeout in N milliseconds from now" (a relative timeout), you need to get the current time with clock_gettime()
(specifying the CLOCK_REALTIME
clock, as that's the clock used by pthread_mutex_timedlock()
) then offset it by N milliseconds and pass the result to pthread_mutex_timedlock()
.
Upvotes: 4