Listing 2: Two threads accessing the same Point
#using <mscorlib.dll>
using namespace System;
using namespace System::Threading;
__gc class Point
{
int x;
int y;
public:
Point()
{
x = 0;
y = 0;
}
void Move(int xor, int yor)
{
/*1a*/ Monitor::Enter(this);
x = xor;
y = yor;
/*1b*/ Monitor::Exit(this);
}
String *ToString()
{
/*2a*/ String *s;
Monitor::Enter(this);
s = String::Format(S"({0},{1})", x.ToString(), y.ToString());
/*2b*/ Monitor::Exit(this);
return s;
}
};
__gc class Th02
{
Point *pnt;
bool mover;
public:
Th02(bool isMover, Point *p)
{
mover = isMover;
pnt = p;
}
void StartUp()
{
if (mover)
{
for (int i = 1; i <= 10000000; ++i)
{
/*3*/ pnt->Move(i, i);
}
}
else
{
for (int i = 1; i <= 10; ++i)
{
/*4*/ Console::WriteLine(pnt); // calls ToString
Thread::Sleep(10);
}
}
}
};
int main()
{
Point *p = new Point;
/*5*/ Th02 *o1 = new Th02(true, p);
/*6*/ Thread *t1 = new Thread(new ThreadStart(o1, &Th02::StartUp));
/*7*/ Th02 *o2 = new Th02(false, p);
/*8*/ Thread *t2 = new Thread(new ThreadStart(o2, &Th02::StartUp));
t1->Start();
t2->Start();
}
End of Listing