无序线程问题 [英] Unordered threads problem
问题描述
我问的问题关于锁在这里 和人民的反应有在我的锁实现没有问题。但我逮住问题。下面是同样的锁实现,我越来越怪异的结果。我希望看到的数字从1开始,但它从5.Example是如下。
类节目
{
静态对象更衣室=新的对象();
静态无效的主要(字串[] args)
{
对于(INT J = 0; J< 100; J ++)
{
(新主题(新ParameterizedThreadStart(dostuff)))启动(J);
}
Console.ReadKey();
}
静态无效dostuff(动态输入)
{
锁(更衣室)
{
Console.WriteLine(输入);
}
}
}
在code是罚款。但你不能保证线程的执行顺序。当我运行code,我得到:
1 3 五 2 4 6 10 9 11 7 12 8 等
如果您需要在指定的顺序运行的线程,你可以考虑使用 ThreadPool.QueueUserWorkItem
代替。
类节目
{
静态对象更衣室=新的对象();
静态的EventWaitHandle clearCount
=新的EventWaitHandle(假,EventResetMode.ManualReset);
静态无效的主要(字串[] args)
{
对于(INT J = 0; J< 100; J ++)
{
ThreadPool.QueueUserWorkItem(dostuff,j)的;
}
clearCount.WaitOne();
}
静态无效dostuff(动态输入)
{
锁(更衣室)
{
Console.WriteLine(输入);
如果(输入== 99)clearCount.Set();
}
}
}
I had asked question about lock in here and people responded there is no problem in my lock implementation. But i catched problem. Here is same lock implementation and i am getting weird result. I expect to see numbers starts from 1 but it starts from 5.Example is at below.
class Program
{
static object locker = new object();
static void Main(string[] args)
{
for (int j = 0; j < 100; j++)
{
(new Thread(new ParameterizedThreadStart(dostuff))).Start(j);
}
Console.ReadKey();
}
static void dostuff(dynamic input)
{
lock (locker)
{
Console.WriteLine(input);
}
}
}
The code is fine. But you cannot guarantee the order the threads are executed in. When I run the code I get:
0 1 3 5 2 4 6 10 9 11 7 12 8 etc
If you need to run the threads in a specified order, you could look into using ThreadPool.QueueUserWorkItem
instead.
class Program
{
static object locker = new object();
static EventWaitHandle clearCount
=new EventWaitHandle(false, EventResetMode.ManualReset);
static void Main(string[] args)
{
for (int j = 0; j < 100; j++)
{
ThreadPool.QueueUserWorkItem(dostuff, j);
}
clearCount.WaitOne();
}
static void dostuff(dynamic input)
{
lock (locker)
{
Console.WriteLine(input);
if (input == 99) clearCount.Set();
}
}
}
这篇关于无序线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!