Atomic updates: Difference between revisions

m
Line 2,634:
child processes to handle the tasks, as this is the standard way
for general PicoLisp applications.
<lang PicoLisp>(deseed *Buckets(in ."/dev/urandom" 15(rd 8))) # Number of buckets
 
(de *Buckets . 15) # Number of buckets
 
# E/R model
(class +Bucket +Entity)
(rel key (+Key +Number)) # Key 1 .. *Buckets
(rel val (+Number)) # Value 1 .. 999
 
 
# Start with an empty DB
(call 'rm "-f" "buckets.db") # Remove old DB (if any)
(pool "buckets.db") # Create new DB file
 
# Create processnew DB file
(pool (tmp "buckets.db"))
 
# Create *Buckets buckets with values between 1 and 999
Line 2,651 ⟶ 2,650:
(new T '(+Bucket) 'key K 'val (rand 1 999)) )
(commit)
 
 
# Pick a random bucket
(de pickBucket ()
(db 'key '+Bucket (rand 1 *Buckets)) )
 
# Create process
(de process (QuadFunction)
(unless (fork)
(seed *Pid) # Ensure local random sequence
(loop
(let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2'
(unless (== B1 B2) # Found two different ones?
(dbSync) # Atomic DB operation
(let (V1 (; B1 val) V2 (; B2 val)) # Get current values
(QuadFunction B1 V1 B2 V2) )
(commit 'upd) ) ) ) ) ) # Close transaction
 
 
# First process
(unless (fork)
(process
(seed *Pid) # Ensure local random sequence
(quote (B1 V1 B2 V2)
(condloop
(let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2'
((> V1 V2)
(dbSync) (dec> B1 'val) # Make them closer to equal # Atomic DB operation
(let (V1 (inc>; B2B1 'val) V2 (; B2 val)) # Get current values
((> V2 V1) (cond
((dec> B2V1 'valV2)
(incdec> B1 'val) ) ) ) ) # Make them closer to equal
(decinc> B2 'val) )
((> V1 V2 V1)
(dec> B2 'val)
(QuadFunctioninc> B1 V1'val) B2) V2) )
(commit (dbSync'upd) # Atomic DBClose operationtransaction
((>wait 1) V1) V2) 0)
 
# Second process
(unless (fork)
(process
(seed *Pid) # Ensure local random sequence
(quote (B1 V1 B2 V2)
(condloop
(let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2'
((> V1 V2 0)
(inc>unless (== B1 'valB2) # RedistributeFound two different themones?
(unlessdbSync) (== B1 B2) # Found two different# Atomic DB ones?operation
(dec> B2 'val) )
(let (>V1 (; B1 val) V2 V1(; 0B2 val)) # Get current values
(inc> B2 'val) (cond
(dec> B1 'val) ) ) ) ((> V1 V2 0)
(inc> B1 'val) # Redistribute them
(let (V1 (; B1 val) V2 (;dec> B2 'val) ) # Get current values
((> V2 V1 0)
(inc> B2 'val)
(dec> B1 'val) ) ) )
(commit 'upd) ) ) ) ) ) # Close transaction
(wait 1) ) ) ) )
 
# Third process
(unless (fork)
(loop
(dbSync) # Atomic DB operation
(let Lst (collect 'key '+Bucket) # Get all buckets
(for This Lst # Print current values
(printsp (: val)) )
(prinl # and total sum
"-- Total: "
(sum '((This) (: val)) Lst) ) )
(rollback)
(wait 2000) ) ) # Sleep two seconds
 
(wait)</lang>
298

edits