从Linux汇编语言中使用pthread_mutex_timedlock

那个设定:

我想在我的32位汇编语言程序中使用pthreads中的pthread_mutex_timedlock函数。 代码如下所示:

 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 

问题是pthread_mutex_timedlock函数只有在立即解锁的情况下才locking互斥锁。

如果此时互斥锁被locking,则函数pthread_mutex_timedlock将立即返回ETIMEDOUT错误,而不等待超时,忽略在timespec结构中设置的值。

问题是:

我做错了什么?

pthread_mutex_timedlock()的超时是一个绝对超时,而不是相对的 – 它会立即返回,因为超时值表示的绝对时间已经过去很久了。

如果你想要一个“从现在开始N毫秒的超时”(一个相对超时),你需要用clock_gettime() (指定CLOCK_REALTIME时钟,因为这是pthread_mutex_timedlock()使用的时钟clock_gettime()得到当前时间,然后用N毫秒,并将结果传递给pthread_mutex_timedlock()