【聚杰网C++】实例解析C++/CLI线程之多任务
| Primary thread terminating t1: i = 0 t1: i = 200000 t1: i = 400000 t1: i = 600000 t2: i = -1000000 t2: i = -800000 t2: i = -600000 t2: i = -400000 t2: i = -200000 t2: i = 0 t2 thread terminating t1: i = 800000 t1: i = 1000000 t1 thread terminating |
如果想让不同的线程由不同的进入点函数开始,只需简单地在同一或不同的类中,定义这些函数就行了(或作为非成员函数)。
同步语句
例2中的主程序有两个线程访问同一Point,其中一个不断地把Point的x与y坐标设置为一些新值,而另一个取回并显示这些值。即使两个线程由同一进入点函数开始执行,通过传递一个值给它们的构造函数,可使每个线程的行为都有所不同。
例2:
| using namespace System; using namespace System::Threading; public ref class Point { int x; int y; public: //定义读写访问器 property int X { int get() { return x; } void set(int val) { x = val; } } property int Y { int get() { return y; } void set(int val) { y = val; } } // ... void Move(int xor, int yor) { /*1a*/ Monitor::Enter(this); X = xor; Y = yor; /*1b*/ Monitor::Exit(this); } virtual bool Equals(Object^ obj) override { // ... if (GetType() == obj->GetType()) { int xCopy1, xCopy2, yCopy1, yCopy2; Point^ p = static_cast /*2a*/ Monitor::Enter(this); xCopy1 = X; xCopy2 = p->X; yCopy1 = Y; yCopy2 = p->Y; /*2b*/ Monitor::Exit(this); return (xCopy1 == xCopy2) && (yCopy1 == yCopy2); } return false; } virtual int GetHashCode() override { int xCopy; int yCopy; /*3a*/ Monitor::Enter(this); xCopy = X; yCopy = Y; /*3b*/ Monitor::Exit(this); return xCopy ^ (yCopy << 1); } virtual String^ ToString() override { int xCopy; int yCopy; /*4a*/ Monitor::Enter(this); xCopy = X; yCopy = Y; /*4b*/ Monitor::Exit(this); return String::Concat("(", xCopy, ",", yCopy, ")"); } }; public ref class ThreadY { Point^ pnt; bool mover; public: ThreadY(bool isMover, Point^ p) { mover = isMover; pnt = p; } void StartUp() { if (mover) { for (int i = 1; i <= 10000000; ++i) { /*1*/ pnt->Move(i, i); } } else { for (int i = 1; i <= 10; ++i) { /*2*/ Console::WriteLine(pnt); // calls ToString Thread::Sleep(10); } } } }; int main() { Point^ p = gcnew Point; /*1*/ ThreadY^ o1 = gcnew ThreadY(true, p); /*2*/ Thread^ t1 = gcnew Thread(gcnew ThreadStart(o1, &ThreadY::StartUp)); /*3*/ ThreadY^ o2 = gcnew ThreadY(false, p); /*4*/ Thread^ t2 = gcnew Thread(gcnew ThreadStart(o2, &ThreadY::StartUp)); t1->Start(); t2->Start(); Thread::Sleep(100); /*5*/ Console::WriteLine("x: {0}", p->X); /*6*/ Console::WriteLine("y: {0}", p->Y); /*7*/ t1->Join(); t2->Join(); } |
调用Sleep休眠100毫秒的目的是为了在可以访问x与y坐标之前,让两个线程开始执行,这就是说,我们想要主线程与其他两个线程竞争坐标值的独占访问。





