关于线程的一个问题

lxc20082008 2009-03-08 06:55:34
MSDN中的一个例子
using System;
using System.Threading;

namespace AutoResetEvent_Examples
{
class MyMainClass
{
//Initially not signaled.
const int numIterations = 100;
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static int number;

static void Main()
{
//Create and start the reader thread.
Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
myReaderThread.Name = "ReaderThread";
myReaderThread.Start();

for(int i = 1; i <= numIterations; i++)
{
Console.WriteLine("Writer thread writing value: {0}", i);
number = i;

//Signal that a value has been written.
myResetEvent.Set();

//Give the Reader thread an opportunity to act.
Thread.Sleep(0);
}

//Terminate the reader thread.
myReaderThread.Abort();
}

static void MyReadThreadProc()
{
while(true)
{
//The value will not be read until the writer has written
// at least once since the last read.
myResetEvent.WaitOne();
Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);
}
}
}
}

我想应该执行结果是
Writer thread writing value:1
ReaderThread reading value:1
Writer thread writing value:2
ReaderThread reading value:2
Writer thread writing value:3
ReaderThread reading value:3
。。。。。。。。。
这样下去,但是在我的计算机上运行后会出现部分数字乱码
...全文
102 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxc20082008 2009-07-01
  • 打赏
  • 举报
回复
谢谢,学习了
EveryCase 2009-03-08
  • 打赏
  • 举报
回复
顶~~~~~~~~~~~~~~~
gomoku 2009-03-08
  • 打赏
  • 举报
回复

//Give the Reader thread an opportunity to act.
Thread.Sleep(0);

Thread.Sleep主动放弃当前的线程剩余的时间片,让其他线程有机会执行。
但是,MyReadThreadProc却不一定就能执行,系统调度可能把运行机会给了其他线程。
这种情况相当于myResetEvent.Set()被连续调用了几次。


而快速地多次触发事件,等待者不一定来得及消化。
比如连续触发三次,可能MyReadThreadProc中的Console.WriteLine才运行一次:

myResetEvent.Set();
myResetEvent.Set();
myResetEvent.Set();


该例子示范了事件等待。但不保证ThreadProc能得到Main中写出的每个值 - 这需要另一个事件(原文如下):
The program logic guarantees that the ThreadProc method will never read the same value two times. It does not guarantee that the ThreadProc method will read every value written by Main. That guarantee would require a second AutoResetEvent lock.

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧