Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

system.once is not thread safe #8895

Open
timotheecour opened this issue Sep 6, 2018 · 2 comments
Open

system.once is not thread safe #8895

timotheecour opened this issue Sep 6, 2018 · 2 comments

Comments

@timotheecour
Copy link
Member

timotheecour commented Sep 6, 2018

system.once isn't thread safe:

template once*(body: untyped): untyped =
  var alreadyExecuted {.global.} = false
  if not alreadyExecuted:
    alreadyExecuted = true
    body

[EDIT] Example

when defined caseSub:
  const N = 10
  var thr: array[N, Thread[int]]
  var count = 0
  proc threadFunc(a: int) {.thread.} =
    once: count.inc
    doAssert count == 1
  proc main =
    for i in 0..<N:
      createThread(thr[i], threadFunc, i)
    joinThreads(thr)
  main()

else:
  import os, strformat
  proc main =
    const nim = getCurrentCompilerExe()
    const exe = "/tmp/z01b"
    const file = currentSourcePath
    # -d:danger
    let cmd = fmt"{nim} c -d:caseSub --threads -o:{exe} {file}"
    echo cmd
    doAssert execShellCmd(cmd) == 0
    for i in 0..<10000:
      let ret = execShellCmd(exe)
      doAssert ret == 0, $i
  main()

Current output

fails after a few iterations: count == 1 [AssertionDefect]

Expected output

works

see also

@timotheecour
Copy link
Member Author

timotheecour commented Nov 10, 2020

probably needs import rlocks or locks?

EDIT: note from @xflywind : see
https://github.com/golang/go/blob/master/src/sync/once.go

@timotheecour timotheecour changed the title race condition for system.once? system.once is not thread safe Dec 1, 2020
@timotheecour
Copy link
Member Author

update: added a minimal repro, see top msg /cc @xflywind

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants