blocking_step.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (c) 2018 David Crawshaw <david@zentus.com>
  2. // Copyright (c) 2021 Ross Light <ross@zombiezen.com>
  3. //
  4. // Permission to use, copy, modify, and distribute this software for any
  5. // purpose with or without fee is hereby granted, provided that the above
  6. // copyright notice and this permission notice appear in all copies.
  7. //
  8. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. //
  16. // SPDX-License-Identifier: ISC
  17. package sqlite
  18. import (
  19. "fmt"
  20. "sync"
  21. "unsafe"
  22. "modernc.org/libc"
  23. "modernc.org/libc/sys/types"
  24. lib "modernc.org/sqlite/lib"
  25. )
  26. // See https://sqlite.org/unlock_notify.html for detailed explanation.
  27. // unlockNote is a C-allocated struct used as a condition variable.
  28. type unlockNote struct {
  29. mu sync.Mutex
  30. wait sync.Mutex // held while fired == false
  31. fired bool
  32. }
  33. func allocUnlockNote(tls *libc.TLS) (uintptr, error) {
  34. ptr := libc.Xcalloc(tls, 1, types.Size_t(unsafe.Sizeof(unlockNote{})))
  35. if ptr == 0 {
  36. return 0, fmt.Errorf("out of memory for unlockNote")
  37. }
  38. un := (*unlockNote)(unsafe.Pointer(ptr))
  39. un.wait.Lock()
  40. return ptr, nil
  41. }
  42. func fireUnlockNote(tls *libc.TLS, ptr uintptr) {
  43. un := (*unlockNote)(unsafe.Pointer(ptr))
  44. un.mu.Lock()
  45. if !un.fired {
  46. un.fired = true
  47. un.wait.Unlock()
  48. }
  49. un.mu.Unlock()
  50. }
  51. func unlockNotifyCallback(tls *libc.TLS, apArg uintptr, nArg int32) {
  52. for ; nArg > 0; nArg-- {
  53. fireUnlockNote(tls, *(*uintptr)(unsafe.Pointer(apArg)))
  54. // apArg is a C array of pointers.
  55. apArg += unsafe.Sizeof(uintptr(0))
  56. }
  57. }
  58. func waitForUnlockNotify(tls *libc.TLS, db uintptr, unPtr uintptr) ResultCode {
  59. un := (*unlockNote)(unsafe.Pointer(unPtr))
  60. if un.fired {
  61. un.wait.Lock()
  62. }
  63. un.fired = false
  64. cbPtr := cFuncPointer(unlockNotifyCallback)
  65. res := ResultCode(lib.Xsqlite3_unlock_notify(tls, db, cbPtr, unPtr))
  66. if res == ResultOK {
  67. un.mu.Lock()
  68. fired := un.fired
  69. un.mu.Unlock()
  70. if !fired {
  71. un.wait.Lock()
  72. un.wait.Unlock()
  73. }
  74. }
  75. return res
  76. }