Created
March 14, 2011 08:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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