You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebAssembly中WASI线程wait&notify失效问题求助

WebAssembly中thread_join模拟实现的问题

我尝试在WebAssembly中模拟thread_join的逻辑:主线程先将mutex设为锁定状态(值为1),启动子线程后,子线程退出前解锁mutex;主线程通过尝试获取并释放mutex来感知子线程退出。

我的WAT代码

(module
  (type $main_type (func))
  (type $simple_type (func (param i32)))
  (type $thread_spawn_type (func (param i32) (result i32)))
  (type $thread_start_type (func (param i32 i32)))
  (import "wasi" "thread-spawn" (func $thread_spawn (type $thread_spawn_type)))
  (func $try_lock_mutex (type $thread_spawn_type) (param $mutex_address i32) (result i32)
    local.get $mutex_address
    i32.const 0 ;; expected
    i32.const 1 ;; locked
    i32.atomic.rmw.cmpxchg
    i32.eqz
  )
   (func $lock_mutex (type $simple_type) (param $mutex_address i32)
      block $done
        loop $retry
          ;; Try to lock the mutex. $tryLockMutex returns 1 if the mutex
          ;; was locked, and 0 otherwise.
          local.get $mutex_address
          call $try_lock_mutex
          br_if $done
          ;; Wait for the other agent to finish with mutex.
          local.get $mutex_address ;; mutex address
          i32.const 1              ;; expected value (1 => locked)
          i64.const -1             ;; infinite timeout
          memory.atomic.wait32
          drop
          br $retry
        end
      end
   )
  (func $unlock_mutex (type $simple_type) (param $mutex_address i32)
      ;; mutex must be locked before by caller
      ;; Unlock the mutex.
      local.get $mutex_address     ;; mutex address
      i32.const 0              ;; 0 => unlocked
      i32.atomic.store

      ;; Notify one agent that is waiting on this lock.
      local.get $mutex_address   ;; mutex address
      i32.const 1            ;; notify 1 waiter
      memory.atomic.notify
      drop
   )
  (func $wait_mutex_lock (type $simple_type) (param $mutex_address i32)
    local.get $mutex_address
    call $lock_mutex
    local.get $mutex_address
    call $unlock_mutex
  )
  (func $wasi_thread_start (type $thread_start_type) (param i32 i32)
     local.get 1
     call $unlock_mutex
  )
  (func $main (type $main_type)
    i32.const 0
    call $lock_mutex
    i32.const 0
    call $thread_spawn
    drop
    i32.const 0
    call $wait_mutex_lock
  )
  (memory (;0;) 4 4 shared)
  (export "wasi_thread_start" (func $wasi_thread_start))
  (export "_start" (func $main))
)

编译与运行命令

  • 编译为WASM文件:wat2wasm.exe mutex.wat --enable-threads -o mutex.wasm
  • 使用Wasmtime运行:wasmtime -W all-proposals=y -S threads .\mutex.wasm

mutex核心代码基于WebAssembly threads提案实现,当前遇到的问题是:子线程始终未解锁mutex,导致主线程陷入无限等待状态。

内容的提问来源于stack exchange,提问作者Ali Qanbari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 23:15:11