My Development Notes

By Haemoglobin
6/21/2011 (revision 3)

Threading

Data structures for parallel programming

Parallel programming in the .NET framework

public static main() {
    //Up to 250 threads, otherwise change .SetMaxThreads, .GetAvailableThreads(out workerThreads, out completionPortThreads)
    ThreadPool.QueueUserWorkItem(RunMe, "Thread 1"); 
}

static void RunMe(object stateInfo) {
    string s = (string)stateInfo; 
    bool b = Thread.CurrentThread.IsBackground; 
}
 public static Main() {
    Thread DoWorkTread = new Thread(new ThreadStart(DoWork)); //Or just new Thread(DoWork); <- C# infers the ThreadStart delegate.
    DoWorkThread.Priority = Highest, AboveNormal, Normal, BelowNormal, Lowest;
    DoWorkThread.Start(); 
    Thread.Sleep(1000); 
    DoWorkThread.Abort(); 

    Thread DoWorkThread = new Thread(DoWorkWithParam); //Inferred new ParameterizedThreadStart(DoWorkWithParam) delegate
    DoWorkThread.Start(40); 
 }

  public static void DoWork() {
    try {
        //work loop
    }
    catch (ThreadAbortException ex) {
        //thread being aborted
    }
    finally {
        //close any open resources
    }
 }

 public static void DoWorkWithParam(object data) {
    int d = (int)data; 
 }
 

Thread.State

  • Unstarted
  • Running
  • Stopped
  • WaitSleepJoin
  • SuspendRequested
  • Suspended
  • AbortRequested
  • Aborted
 Multiply m = new Multiply("Hello", 13, 2, new ResultDelegate(ResultCallback));

 t = new Thread(new ThreadStart(m.Go())); 
 t.Start(); 
 t.Join();  //this thread waits for completion

 public class Multiply {
    int x, y; 
    private ResultDelegate callback; 
    ReaderWriterLock rwl = new ReaderWriterLock(); 
    public void Go() {
        lock(this) {
            callback(x*y); 
        }
        //or 
        rwl.Aquire[Reader|Writer]Lock(100000); //timeout
        rwl.Release[Reader|Writer]Lock(); //Writer lock is exclusive, no readers allowed

        //The following operations are atomic. Needed if multiple threads writing to a variable since 
        //an assignment is both a read and a write, another thread could sneak in between
        Interlocked.Increment(x);
        Interlocked.Add(x);
        Interlocked.Exchange(x, 10);
        Interlocked.Increment(x, 35);
    }
 }

 static AutoResetEvent[] waitHandles = new AutoResetEvent[] { new AutoResetEvent(false), new AutoResetEvent(false) }

ThreadPool.QueueUserWorkItem(DoStuff, waitHandles[0]); 
ThreadPool.QueueUserWorkItem(DoStuff, waitHandles[1]);
WaitHandle.Wait[All|Any](waitHandles); 

static void DoTask(object waitHandle) {
    ((AutoResetEvent)waitHandle).Set(); 
}
 

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin