c#多线程编程笔记2

来源:互联网 发布:网络之父的名称 编辑:程序博客网 时间:2024/04/30 06:55

第三部分   线程的同步

同步的意思是在多线程程序中,为了使两个或多个线程之间,对分配临界资源的分配问题,要如何分配才能使临界资源在为某一线程使用的时候,其它线程不能再使用,这样可以有效地避免死锁与脏数据。脏数据是指两个线程同时使用某一数据,造成这个数据出现不可预知的状态!在C#中,对线程同步的处理有如下几种方法:

a)        等待事件:当某一事件发生后,再发生另一件事。

例子3

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

 

namespace ConsoleApplication1

{

    public class ClassCounter

    {

        protected int m_iCounter = 0;

        public void Increment()

        {

            m_iCounter++;

        }

        public int Counter

        {

            get

            {

                return m_iCounter;

            }

        }

    }

    public class EventClass

    {

        protected ClassCounter m_protectedResource = new ClassCounter();

        protected ManualResetEvent m_manualResetEvent = new ManualResetEvent(false);//ManualResetEvent(initialState),initialState如果为true,则将初始状态设置为终止;如果为false,则将初始状态设置为非终止。

        protected void ThreadOneMethod()

        {

            m_manualResetEvent.WaitOne();//在这里是将入口为ThreadOneMethod的线程设为等待

            m_protectedResource.Increment();

            int iValue = m_protectedResource.Counter;

            System.Console.WriteLine("{Thread one} - Current value of counter:"+iValue.ToString());

        }

        protected void ThreadTwoMethod()

        {

            int iValue = m_protectedResource.Counter;

            Console.WriteLine("{Thread two}-current value of counter;"+iValue.ToString());

            m_manualResetEvent.Set();//激活等待的线程

        }

        static void Main()

        {

            EventClass exampleClass = new EventClass();

 

            Thread threadOne = new Thread(new ThreadStart(exampleClass.ThreadOneMethod));

            Thread threadTwo = new Thread(new ThreadStart(exampleClass.ThreadTwoMethod));

 

            threadOne.Start();//请注意这里,这里是先执行线程1

            threadTwo.Start();//再执行线程2,那么线程2的值应该比线程1大,但结果相反

 

            Console.ReadLine();

        }

    }

}

 

 

ManualResetEvent它允许线程之间互相发消息。

结果如下:
 
原创粉丝点击