Gauche Devlog

< Automatic port selection for httpd | Comparators >


Running code once and only once

It occasionally pops up---you have a piece of code you need to run once, but only once, even requested from multiple threads simultaneously. It's not a difficult problem, but can be boring enough to be worth to have a library procedure on some languages.

Every time I encounter an instance of such case it occurs to me to add a library procedure, then I think again to drop the idea, for it's just as trivial as the following in Scheme:

(define (run-once thunk)
  (let1 v (delay (thunk))
    (^[] (force v))))

(It may depend on implementations, but at least on Gauche, force is thread-safe and the above just works in multi-threaded environment.)

Do you think it is worth to have it in a library?

Tags: delay, multithread

Past comment(s)

pclouds (2016/03/14 11:53:50):

Perhaps a note in the document.

shiro (2016/03/14 19:11:19):

Good idea. Thanks.

Post a comment