Task: Atomic updates



C#: using System; 
using System.Threading; 
public class ThreadSafeBuckets
{
    
    
    Random rand = new Random();
    int[] Buckets;
    object[] locks; 
    public int BucketCount { get; private set; }
    public ThreadSafeBuckets(int bucketcount)
    {
        
        BucketCount = bucketcount;
        Buckets = new int[bucketcount];
        locks = new object[bucketcount];
        int startingtotal = 0;
        for (int i = 0; i < BucketCount; i++)
        {
            locks[i] = new object();
            Buckets[i] = rand.Next(30);
            startingtotal += Buckets[i];
        }
        
        Console.WriteLine("Starting total: " + startingtotal);
    }
    public int GetBucketValue(int i)
    {
        return Buckets[i];
    }
    public void Transfer(int i, int j, int amount)
    {
        
        if (i > BucketCount || j > BucketCount || i < 0 || j < 0 ||
            i == j || amount < 0)
            return;

        
        lock (locks[Math.Min(i, j)])
            lock (locks[Math.Max(i, j)])
            {
                
                amount = Math.Min(amount, Buckets[i]);

                
                Buckets[i] -= amount;
                Buckets[j] += amount;
            }
    }

    public void PrintBuckets()
    {
        int counter = 0;
        
        for (int i = 0; i < BucketCount; i++)
        {
            Monitor.Enter(locks[i]);
            Console.Write(Buckets[i] + " ");
            counter += Buckets[i];
        }
        
        Console.Write("= " + counter);
        Console.WriteLine();

        foreach (var l in locks)
            Monitor.Exit(l);
    }
}

class Program
{
    static ThreadSafeBuckets TSBs;

    public static void Main(){
        
        TSBs = new ThreadSafeBuckets(10);
        TSBs.PrintBuckets();
        
        new Thread(new ThreadStart(EqualizerThread)).Start();
        Thread.Sleep(1);
        
        new Thread(new ThreadStart(RandomizerThread)).Start();
        
        PrinterThread();
    }
    
    static void EqualizerThread()
    {
        Random rand = new Random();
        while (true)
        {
            
            int b1 = rand.Next(TSBs.BucketCount);
            int b2 = rand.Next(TSBs.BucketCount);
            
            int diff = TSBs.GetBucketValue(b1) - TSBs.GetBucketValue(b2);
            
            if (diff < 0)
                TSBs.Transfer(b2, b1, -diff / 2);
            else
                TSBs.Transfer(b1, b2, diff/2);
        }
    }
    
    static void RandomizerThread()
    {
        Random rand = new Random();
        while (true)
        {
            int b1 = rand.Next(TSBs.BucketCount);
            int b2 = rand.Next(TSBs.BucketCount);
            int diff = rand.Next(TSBs.GetBucketValue(b1));
            TSBs.Transfer(b1, b2, diff);
        }
    }
    
    static void PrinterThread()
    {
        while (true)
        {
            Thread.Sleep(50); 
            TSBs.PrintBuckets();
        }
    }
}





Python: from __future__ import with_statement 
import threading
import random
import time

terminate = threading.Event()

class Buckets:
    def __init__(self, nbuckets):
        self.nbuckets = nbuckets
        self.values = [random.randrange(10) for i in range(nbuckets)]
        self.lock = threading.Lock()

    def __getitem__(self, i):
        return self.values[i]

    def transfer(self, src, dst, amount):
        with self.lock:
            amount = min(amount, self.values[src])
            self.values[src] -= amount
            self.values[dst] += amount

    def snapshot(self):
        
        with self.lock:
            return self.values[:]

def randomize(buckets):
    nbuckets = buckets.nbuckets
    while not terminate.isSet():
        src = random.randrange(nbuckets)
        dst = random.randrange(nbuckets)
        if dst!=src:
            amount = random.randrange(20)
            buckets.transfer(src, dst, amount)

def equalize(buckets):
    nbuckets = buckets.nbuckets
    while not terminate.isSet():
        src = random.randrange(nbuckets)
        dst = random.randrange(nbuckets)
        if dst!=src:
            amount = (buckets[src] - buckets[dst]) // 2
            if amount>=0: buckets.transfer(src, dst, amount)
            else: buckets.transfer(dst, src, -amount)

def print_state(buckets):
    snapshot = buckets.snapshot()
    for value in snapshot:
        print '%2d' % value,
    print '=', sum(snapshot)


buckets = Buckets(15)


t1 = threading.Thread(target=randomize, args=[buckets])
t1.start()


t2 = threading.Thread(target=equalize, args=[buckets])
t2.start()


try:
    while True:
        print_state(buckets)
        time.sleep(1)
except KeyboardInterrupt: 
    terminate.set()


t1.join()
t2.join()