Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Created March 14, 2011 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarnacious/868896 to your computer and use it in GitHub Desktop.
Save tarnacious/868896 to your computer and use it in GitHub Desktop.
C# implementation of a circular message chain of n nodes, which pass a message around m times. This time with threads.
using System;
using System.Threading;
public class MessageChainThreads
{
public static AutoResetEvent CreateNode(AutoResetEvent triggerEvent, int messages)
{
var waitEvent = new AutoResetEvent(false);
CreateThread(waitEvent, triggerEvent, messages);
return waitEvent;
}
public static void CreateThread(AutoResetEvent waitEvent, AutoResetEvent triggerEvent, int messages)
{
Console.WriteLine("Spawing a thread");
Thread t = new Thread ( () => {
for(int i = 0; i < messages; i++) {
waitEvent.WaitOne();
Console.WriteLine("Triggered thread. Loop {0}", i);
triggerEvent.Set();
};
Console.WriteLine ("Killing thread.");
});
t.Start();
}
public static void Main()
{
var messages = 3;
var nodes = 3;
// Create the message chain of threads
var startNodeEvent = new AutoResetEvent(false);
var nextNodeEvent = startNodeEvent;
for(int i = 0; i < nodes - 1; i++)
{
nextNodeEvent = CreateNode(nextNodeEvent, messages);
}
// Link up the first and last thread events in a thread.
CreateThread(startNodeEvent, nextNodeEvent, messages);
// Go, go, go!
startNodeEvent.Set();
}
}
$ gmcs message_chain_threads.cs
$ ./message_chain_threads.exe
Spawing a thread
Spawing a thread
Spawing a thread
Triggered thread. Loop 0
Triggered thread. Loop 0
Triggered thread. Loop 0
Triggered thread. Loop 1
Triggered thread. Loop 1
Triggered thread. Loop 1
Triggered thread. Loop 2
Killing thread.
Triggered thread. Loop 2
Killing thread.
Triggered thread. Loop 2
Killing thread.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment