

Task

Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:

 get the current value of any bucket
 remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative

In order to exercise this data type, create one set of buckets, and start three concurrent tasks:

 As often as possible, pick two buckets and make their values closer to equal.
 As often as possible, pick two buckets and arbitrarily redistribute their values.
 At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.


The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.


This task is intended as an exercise in atomic operations.   The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.




Randomize Timer
Dim Shared As Uinteger cubo(1 To 10), a, i
For i As Uinteger = 1 To 10 
    cubo(i) = Int(Rnd * 90)
Next i
 
Function Display(cadena As String) As Uinteger
    Dim As Uinteger valor
    Print cadena; Spc(2);
    For i As Uinteger = 1 To 10
        valor += cubo(i)
        Print Using "###"; cubo(i);
    Next i
    Print " Total:"; valor
    Return valor
End Function
 
Sub Flatten(f As Uinteger)
    Dim As Uinteger f1 = Int((f / 10) + .5), f2
    For i As Uinteger = 1 To 10
        cubo(i) = f1
        f2 += f1
    Next i
    cubo(10) += f - f2
End Sub
 
Sub Transfer(a1 As Uinteger, a2 As Uinteger)
    Dim As Uinteger temp = Int(Rnd * cubo(a1))
    cubo(a1) -= temp
    cubo(a2) += temp
End Sub
 
a = Display("        Display:")   ' show original array
Flatten(a)                        ' flatten the array
a = Display("        Flatten:")   ' show flattened array
Transfer(3, 5)                    ' transfer some amount from 3 to 5
Display(" 19 from 3 to 5:")       ' show transfer array
Sleep