2016年7月7日木曜日

Threading

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

namespace Thread1
{

    class TestThread
    {
        // THREAD_NUM個のスレッドを立てる。
        // それぞれのスレッドの中でnumをROOP_NUM回インクリメントする。
        static void Main()
        {
            const int ThreadNum = 20;
            const int LoopNum = 20;

            int num = 0;//複数のスレッドから同時にアクセスされる

            var syncObject = new object();

            Parallel.For(0, ThreadNum, i =>
            {
                for (int j = 0; j < LoopNum; j++)
                {
                    //Monitorクラスを簡略化
                    lock (syncObject)
                    {
                        //クリティカルセクション
                        int tmp = num;
                        Thread.Sleep(1);
                        num = tmp + 1;

                    }



                    /*
                                        Monitor.Enter(syncObject);//MonitorクラスのEnterでロックを取得
                                        try
                                        {
                                            //クリティカルセクション
                                            int tmp = num;
                                            Thread.Sleep(1);
                                            num = tmp + 1;
                                        }
                                        finally
                                        {
                                            //ロック解放
                                            Monitor.Exit(syncObject);
                                        }
                                        */

                }
            });

            Console.Write("{0} (期待値{1})\n", num, ThreadNum * LoopNum);
            Console.ReadLine();
        }
    }

    //class TaskSample
    //{
    //    static void Main(string[] args)
    //    {
    //        const int N = 3;
    //        //並列処理が行われる
    //        //idの箇所は、デリゲート。名前はなんでもよい。
    //        Parallel.For(0, N, id =>
    //        {
    //            Random rnd = new Random();
    //            for (int i = 0; i < 10; ++i)
    //            {
    //                // ランダムな間隔で処理を一時中断
    //                Thread.Sleep(rnd.Next(50, 100));
    //                Console.Write("{0} (ID: {1})\n", i, id);
    //            }
    //        });
    //        // 並行して動かしている処理がすべて終わるまで、自動的に待つ
    //    }
    //}
}

0 件のコメント:

コメントを投稿