【问题标题】:pthread_mutex_timedlock use from Linux assembly languagepthread_mutex_timedlock 从 Linux 汇编语言中使用
【发布时间】:2017-02-05 17:56:51
【问题描述】:

设置:

我正在尝试在我的 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 函数只有在立即解锁互斥体时才会锁定它。

如果此时互斥锁被锁定,函数pthread_mutex_timedlock 立即返回ETIMEDOUT 错误,无需等待超时,忽略timespec 结构中设置的值。

问题:

我做错了什么?

【问题讨论】:

  • 使用调试器和/或 ltrace 查看它是如何被调用的。另外,请发布minimal reproducible example,以便我们也可以尝试它,而无需花时间让您的 sn-p 可运行。

标签: c linux assembly pthreads


【解决方案1】:

pthread_mutex_timedlock() 的超时是绝对 超时,而不是相对的 - 它会立即返回,因为您的超时值所代表的绝对时间早已过去。

如果您想要“从现在开始以 N 毫秒为单位的超时”(相对超时),您需要使用 clock_gettime() 获取当前时间(指定 CLOCK_REALTIME 时钟,因为这是 pthread_mutex_timedlock() 使用的时钟)然后将其偏移 N 毫秒并将结果传递给pthread_mutex_timedlock()。

【讨论】:

  • 没错!这是非常非常反直觉的。 :( 另外,对 timespec 字段的处理并不明显。需要在 1e9 ns 上携带 ns 字段。
猜你喜欢
  • 2014-12-08
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 2011-05-11
相关资源
最近更新 更多