RingDotNetfor Ring

Collections for many threads

The classes of System.Collections.Concurrent are safe when several threads use them at the same time. This lesson shows the queue, the stack, the blocking collection and the dictionary, and how closed generic types look when no Ring class exists for them.

What you will learn#

Why#

If two threads add to one List at the same moment, the list can lose an item or break. The concurrent collections do each step (add, remove, "add if missing") as one indivisible step. They are the tool for a producer that adds work and a consumer that takes it. The program in this lesson uses one thread, so that its output is always the same; the calls are the same as in a program with many threads. (The tutorial Tasks that wait shows tasks.)

The program#

samples/UsingDotNet/tutorials/ch04_concurrent_collections.ring
# collections for many threads - ConcurrentQueue, ConcurrentStack, BlockingCollection and ConcurrentDictionary
load "dotnet.ring"

using {
	"System"
	"System.Collections.Concurrent"
}

func main

	# The collections of System.Collections.Concurrent are safe when several threads use them at the same time: the 'is it
	# there? then change it' steps are done as ONE step. They are generic, so they are made with dnNewGeneric (a type name,
	# the type arguments, the constructor values).
	cInt = "System.Int32"
	cText = "System.String"

	# 1. ConcurrentQueue: first in, first out. TryDequeue answers [ success, item ] (an out parameter comes back as a list).
	oQueue = new ConcurrentQueue([ :typeArguments = [cText] ])
	for cName in ["Ann","Bob","Cy"]
		oQueue.Enqueue(cName)
	next
	? "1. queue of " + oQueue.Count + " names, first = " + oQueue.TryPeek()[2]
	while not oQueue.IsEmpty
		aItem = oQueue.TryDequeue()
		? "   dequeued " + aItem[2]
	end
	? "   an empty queue answers: success = " + oQueue.TryDequeue()[1]

	# 2. ConcurrentStack: last in, first out. This closed generic type has no Ring class, so the objects of dnNewGeneric are
	#    used in the plain style: callMethod(name, [arguments]) and getProp(name).
	oStack = new ConcurrentStack([ :typeArguments = [cInt] ])
	for n = 1 to 3
		oStack.Push(n)
	next
	nFirst = oStack.TryPop()[2]
	nSecond = oStack.TryPop()[2]
	? nl + "2. stack: pop gives " + nFirst + " then " + nSecond + ", " + oStack.Count + " left"

	# 3. BlockingCollection: a queue for a producer and a consumer. Take waits while the queue is empty; CompleteAdding says
	#    that nothing more will come, and then IsCompleted becomes true when the queue is empty.
	oBlocking = new BlockingCollection([ :typeArguments = [cInt] ])
	for n = 1 to 5
		oBlocking.Add(n * n)
	next
	oBlocking.CompleteAdding()
	cTaken = ""
	while not oBlocking.IsCompleted
		cTaken += "" + oBlocking.Take(NULL) + " "
	end
	? nl + "3. blocking collection, taken in order: " + cTaken

	# 4. A bounded queue holds at most N items: Add waits when it is full, TryAdd answers at once
	oSmall = new BlockingCollection([ :typeArguments = [cInt], :boundedCapacity = 2 ])
	? nl + "4. bounded to 2: TryAdd gives " + oSmall.TryAdd(10) + ", " + oSmall.TryAdd(20) + ", " + oSmall.TryAdd(30) + " (the third does not fit)"

	# 5. ConcurrentDictionary: TryAdd, TryUpdate (key, new value, the value we expect) and TryRemove
	oCount = new ConcurrentDictionary([ :typeArguments = [cText,cInt] ])
	for cWord in ["red","green","red","blue","red","green"]
		oCount.TryAdd(cWord,0)          # does nothing when the key exists
		nOld = oCount.Item(cWord)
		oCount.TryUpdate(cWord,nOld + 1,nOld)
	next
	? nl + "5. word counts: red = " + oCount.Item("red") + ", green = " + oCount.Item("green") + ", blue = " + oCount.Item("blue")
	? "   TryAdd of an existing key: " + oCount.TryAdd("red",99) + " (the value stays " + oCount.Item("red") + ")"
	aRemoved = oCount.TryRemove("blue")
	? "   TryRemove(blue): success = " + aRemoved[1] + ", the removed value was " + aRemoved[2] + ", keys left: " + oCount.Count
Output
1. queue of 3 names, first = Ann
   dequeued Ann
   dequeued Bob
   dequeued Cy
   an empty queue answers: success = 0

2. stack: pop gives 3 then 2, 1 left

3. blocking collection, taken in order: 1 4 9 16 25 

4. bounded to 2: TryAdd gives 1, 1, 0 (the third does not fit)

5. word counts: red = 3, green = 2, blue = 1
   TryAdd of an existing key: 0 (the value stays 3)
   TryRemove(blue): success = 1, the removed value was 1, keys left: 2
Note

This program uses a few generic functions (dnNewGeneric, callMethod, getProp) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Generic types#

These classes are generic (ConcurrentQueue<T>), so a Ring program creates a closed type with dnNewGeneric(type, [type arguments], [constructor values]). Some closed types have a Ring class and work like any object (the queue of names in step 1: oQueue.Enqueue(...), oQueue.Count); for the others the object is a plain DotNetObject and you use callMethod("Name", [arguments]) and getProp("Name") (Core concepts). The result is the same, only the way of writing differs. A dictionary item is read with callMethod("get_Item", [key]).

Try methods#

TryDequeue, TryPop, TryPeek, TryRemove end with an out value. In Ring they return a list: [ success, value ]; they are called without the out argument. When the collection is empty, success is 0 and the value is meaningless — check it first.

Queue and stack#

A queue is first in, first out; a stack is last in, first out: pushes of 1, 2, 3 pop as 3, 2, then 1 is left.

BlockingCollection#

Take waits when the collection is empty, which is what a consumer wants: it sleeps until a producer adds something. When the producer is finished it calls CompleteAdding; after that IsCompleted becomes true as soon as the collection is empty, and a loop while not IsCompleted ends cleanly. Without CompleteAdding the consumer would wait for ever. A bounded collection (capacity 2) makes Add wait when it is full — the producer cannot run ahead of the consumer; TryAdd does not wait and answers true or false.

Warning

In one thread Take on an empty collection that is not completed waits for ever. The loop in the program is safe because CompleteAdding was called first and IsCompleted is tested before each Take.

ConcurrentDictionary#

TryAdd adds a key only when it is missing (it answers false otherwise and keeps the old value). TryUpdate(key, new, expected) changes a value only if it is still the expected one — so two threads that both read 5 cannot both write 6 and lose a count: the second one fails and must read again. TryRemove returns [ success, removed value ].

What you learned#

Exercises#

  1. Count the letters of a text in a ConcurrentDictionary with TryAdd and TryUpdate.
  2. Write a function drain(oQueue) that returns all the items of a ConcurrentQueue as a Ring list.
  3. Fill a bounded collection (size 3) with TryAdd and print what was refused.
  4. Use ConcurrentBag (an unordered collection) and compare it with the queue.

Next#

Enums and flags

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.