【IT168 技术】我们可以在计算机上运行各种计算机软件程序。每一个运行的程序可能包括多个独立运行的线程(Thread)。线程(Thread)是一份独立运行的程序,有自己专用的运行栈。线程有可能和其他线程共享一些资源,比如,内存,文件,数据库等。当多个线程同时读写同一份共享资源的时候,可能会引起冲突。线程同步可以采用多种方式,下面我们就来了解一下线程同步的多种实现方法。
1、AutoResetEvent
AutoResetEvent 允许线程通过发信号互相通信。通常,此通信涉及线程需要独占访问的资源(MSDN)
访问完独占资源后的线程,通过发送信号通知其它等待线程可以开始抢占资源了,最终已独占的形式访问资源。
AutoResetEvent 初始化时可以设置 new AutoResetEvent (False) 即刚开始无信号,所有等待线程都在等待信号的发出,如为True,则刚开始将有一个线程能马上获得信号进入独占资源直到发出信号。
AutoResetEvent 初始化时如果为True 则有信号,否则为无信号,当每次Set()的时候会自动释放一个等待的线程,与ManualResetEvent不同的是: 顾名思义 AutoResetEvent :在释放一个等待线程后,此同步事件会在发出相应的信号时自动重置事件等待句柄,自动重置事件通常用来一次为一个线程提供对资源的独占访问。而ManualResetEvent则是需要手动重置事件等待句柄,所以并不能保证对资源的独占访问。
class Program
{
private static AutoResetEvent AutoReset = new AutoResetEvent(true);
static void Main(string[] args)
{
//自动重置
AutoResetEventText();
}
static void AutoResetEventText()
{
for (int i = 0; i < 4; i++)
{
Thread tr = new Thread(doing);
tr.Start(i);
}
Console.Read();
}
static void doing(object threadName)
{
AutoReset.WaitOne();
int i = 0;
while (i < 10)
{
Thread.Sleep(10);
Console.WriteLine(threadName + " " + i++);
}
AutoReset.Set();
Console.WriteLine(threadName + "over ");
}
}
{
private static AutoResetEvent AutoReset = new AutoResetEvent(true);
static void Main(string[] args)
{
//自动重置
AutoResetEventText();
}
static void AutoResetEventText()
{
for (int i = 0; i < 4; i++)
{
Thread tr = new Thread(doing);
tr.Start(i);
}
Console.Read();
}
static void doing(object threadName)
{
AutoReset.WaitOne();
int i = 0;
while (i < 10)
{
Thread.Sleep(10);
Console.WriteLine(threadName + " " + i++);
}
AutoReset.Set();
Console.WriteLine(threadName + "over ");
}
}