我有一个带有两个函数的线程类:
using namespace System::Threading;
public ref class SecThr
{
public:
int j;
void wralot()
{
for (int i=0; i<=400000;i++)
{
j=i;
if ((i%10000)==0)
Console::WriteLine(j);
}
}
void setalot()
{
Monitor::Enter(this);
for (int i=0; i<=400000;i++)
{
j=7;
}
Monitor::Exit(this);
}
};
int main(array<System::String ^> ^args)
{
Console::WriteLine("Hello!");
SecThr^ thrcl=gcnew SecThr;
Thread^ o1=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::wralot));
Thread^ o2=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::setalot));
o2->Start();
o1->Start();
o1->Join();
o2->Join();
因此,为了锁定“ setalot”功能,我使用了MOnitor :: Enter-Exit块。但是输出就像我只运行一个带有“ wralot”功能的线程
0 10000 20000 30000 40000 7 //这里是“ setalot”功能60000 e tc
为什么所有输出数据都不能通过“ setalot”函数更改为const(7)
我认为您误解了Monitor::Enter
。它只是一个协作锁-wralot
根本不尝试获取该锁,所以操作setalot
不会对其产生影响。目前尚不清楚,为什么由于以下原因而期望获得恒定的输出7-setalot
如果wralot
确实尝试获得锁,则仅意味着其中一个将“获胜”,而另一个将不得不等待。如果wralot
必须等待,则setalot
运行时将没有任何输出,然后wralot
继续执行操作-包括在每次迭代时都设置j
为i
。
所以基本上,两个线程开始,并setalot
很快将j
到7
了很多次......这可能在计算机方面的瞬息完成,具有比较Console.WriteLine
调用。我建议您Console::WriteLine
在的末尾添加一个呼叫,setalot
以便您可以看到通话结束的时间。显然在那之后,它是完全不相关的-这就是为什么您看到60000、70000等的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句