从Linux汇编语言使用pthread_mutex_timedlock 设置:
我试图在32位汇编语言程序中使用从Linux汇编语言使用pthread_mutex_timedlock 设置:,c,linux,assembly,pthreads,C,Linux,Assembly,Pthreads,我试图在32位汇编语言程序中使用pthread中的pthread\u mutex\u 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_time
pthread
中的pthread\u mutex\u 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\u mutex\u timedlock
函数仅在互斥锁立即解锁时锁定互斥锁
如果此时锁定了互斥锁,则函数pthread\u mutex\u timedlock
会立即返回,并显示ETIMEDOUT
错误,而不等待超时,忽略timespec
结构中设置的值
问题是:
我做错了什么?pthread\u mutex\u timedlock()的超时是一个绝对超时,而不是相对超时-它会立即返回,因为超时值表示的绝对时间早已过去
如果您想要“从现在起以N毫秒为单位的超时”(相对超时),则需要使用
clock\u gettime()
获取当前时间(指定clock\u REALTIME
clock,因为这是pthread\u mutex\u timedlock()
使用的时钟),然后将其偏移N毫秒,并将结果传递给pthread\u mutex\u timedlock()
使用调试器和/或ltrace查看如何调用它。另外,发布一篇文章,这样我们也可以尝试一下,而不必花时间让你的代码片段可以运行。是的,没错!这是非常非常违反直觉的(此外,timespec字段的处理不明显。需要在1e9 ns上携带ns字段。