新文章

2012年8月24日 星期五

[C#]關於Lock機制與multithread實作

一般情況下使用multithreads處理,會有critical section問題,用一個簡單方法就是C#的monitor機制
lock(object) ,能避免critical section問題,但相對的會帶來效能問題,例如500人輪流搬10張桌子,一次限制只能一個人搬,那消耗時間會非常漫長!之後簡談之。



這裡簡單列出使用lock機制範例(暫不考慮效能問題)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AsynchronousSample
{
    //Multiprocessing with lock
    class Sample1
    {
        int count;
        private object _lock = new object();
        public int Max
        {
            get;
            set;
        }
        public void Increase()
        {
            for (int i = 0; i < Max; i++)
            {
                //lock限制同一時間內只能有一個thread處理
                //lock的目標並不是物件,而是程式碼區段,只有被lock包覆的程式區段才會有作用。
                lock (_lock)
                {
                    count++;
                }
            }
        }
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[500];
            Sample1 s1 = new Sample1() { Max = 10000 };
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(s1.Increase);
                threads[i].Start();
            }
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Join();
            }
            Console.WriteLine("{0}", s1.count);
            Console.ReadLine();
        }
    }
}

沒有留言:

張貼留言