0

I have a simple function that I use to cache values. I use a hash table as a cache. The cache will be accessed from different threads and I want to use atomic boxes for controlling the access from different threads. So far I have this code

; Define the local hash table we will use.
(define cache (make-atomic-box (make-hash-table)))

(define-public (make-cache ITEM fv)
  (let ((val (hash-ref (atomic-box-ref cache) ITEM)))
      (if val 
        val
        (begin 
          (hash-set! cache ITEM fv) ;;this where I want to use atomic box update functions
          fv
        ))
  )

)

Now, it is not clear to me how to wrap one of the atomic box update functions (atomic-box-set!, atomic-box-swap! or atomic-box-compare-and-swap! ) around the hash-set function to add new values to the hash-table.

So how I can use atomic boxes for updating hash-tables?

xabush
  • 849
  • 1
  • 13
  • 29

1 Answers1

0

Since hashes are mutable, you can simply stack the calls to the hash and the box as (hash-set! (atomic-box-ref cache) ITEM fv).

If you were dealing with an immutable value, you'd need to copy the value out (atomic-box-ref) and write the processed value in (atomic-box-set!) individually. atomic-box-swap! combines these two into a single operation.

erkin
  • 535
  • 1
  • 5
  • 11