Click here to Skip to main content
15,895,777 members
Articles / Programming Languages / C#

An Introduction to Threads, Critical Sections, and Synchronization

Rate me:
Please Sign up or sign in to vote.
4.00/5 (16 votes)
29 Sep 2008CPOL5 min read 67.7K   254   42  
With the days of the single cored processor drawing to a close and users demanding more robust user interfaces by the day, knowledge of multi-threaded programming techniques is quickly becoming a requirement of any competitive application developer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace threadtesting
{
    class crashtest_02
    {
        private const int thread_count = 30;
        private const int thread_items = 1000;

        private List<string> shared_data = new List<string>();
        private List<Thread> threads = new List<Thread>();
        bool begin = false;

        Mutex mut = new Mutex();

        public crashtest_02()
        {
            for (int i = 0; i < thread_count; i++)
                threads.Add(new Thread(Work));
            for (int i = 0; i < thread_count; i++)
                threads[i].Start(i.ToString());

            begin = true;

            for (int i = 0; i < thread_count; i++)
                threads[i].Join();

            for (int i = 0; i < shared_data.Count; i++)
                Console.WriteLine(shared_data[i]);
            Console.WriteLine("Finished.");
            Console.ReadKey();
        }

        private void Work(object param)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            while (!begin) Thread.Sleep(1);

            string id = (string)param;
            string data = "abc - " + id;
            for (int i = 0; i < thread_items; i++)
            {
                mut.WaitOne();
                shared_data.Add(data);
                mut.ReleaseMutex();
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions