Chris Vine <[email protected]> writes:

> On Fri, 26 May 2017 12:37:47 +0200
> [email protected] wrote:
>> Hello,
>> 
>> I'm making a simple program that processes a lot of mail in separate
>> guile threads.
>> 
>> I would like a counter of how many messages have been processed so I
>> made an attempt with atomics.
>> 
>> first:
>>     (define *msgcount* (make-atomic-box 0))
>> 
>> and later:
>>     (atomic-box-swap! *msgcount* (+ 1 (atomic-box-ref *msgcount*)))
>> 
>> This of course doesn't work very well, and I didnt expect it to
>> either. (usually the count is low by a couple of hundred messages)
>> 
>> So basically, how do I get something similar to the swap! function in
>> clojure? Did I miss something in the documentation for guiles atomics?
>> 
>> I think I expected to be able to do the following:
>>     (atomic-box-swap! *msgcount* (lambda (atom) (+ 1 (atomic-box-ref
>> atom))))
>
> That won't work.  You have to use atomic-box-compare-and-swap!, in order
> to detect interleaving by other threads.  For more on this, google
> "compare and swap".

I wound up with this, is there some better way to do this? Feels a bit verbose.

(define (incatom atom)
  (let ((expected (atomic-box-ref atom)))
    (while (not (= expected (atomic-box-compare-and-swap! atom expected (+ 1 
expected))))
      (set! expected (atomic-box-ref atom)
      ))))



>
>
>
-- 
Joakim Verona
[email protected]



Reply via email to