Instance parsing thread state persistence of C++/CLI threads

Source: Internet
Author: User

Other forms of synchronization

We can use class monitor and some functions in class thread to directly control the synchronization of threads, see Example 1.

Example 1:

using namespace System;
using namespace system::threading;
int main ()
{
/*1*/messagebuffer^ m = gcnew messagebuffer;
/*2a*/processmessages^ pm = gcnew processmessages (m);
/*2b*/thread^ PMT = gcnew Thread (gcnew threadstart (pm,&processmessages::P rocessmessagesentrypoint));
/*2c*/Pmt->start ();
/*3a*/createmessages^ cm = gcnew createmessages (m);
/*3b*/thread^ CMT = gcnew Thread (gcnew threadstart (cm, &createmessages::createmessagesentrypoint));
/*3c*/Cmt->start ();
/*4*/Cmt->join ();
/*5*/Pmt->interrupt ();
/*6*/Pmt->join ();
Console::WriteLine ("Primary thread terminating");
}
Public ref class Messagebuffer
{
string^ MessageText;
Public
void Setmessage (string^ s)
{
/*7*/Monitor::enter (this);
MessageText = s;
/*8*/Monitor::P ulse (this);
Console::WriteLine ("Set new message {0}", MessageText);
Monitor::exit (this);
}
void ProcessMessages ()
{
/*9*/Monitor::enter (this);
while (true)
{
Try
{
/*10*/monitor::wait (this);
}
catch (threadinterruptedexception^ e)
{
Console::WriteLine ("ProcessMessage interrupted");
Return
}
Console::WriteLine ("processed new message {0}", MessageText);
}
Monitor::exit (this);
}
};
Public ref class Createmessages
{
messagebuffer^ msg;
Public
Createmessages (messagebuffer^ m)
{
msg = m;
}
void Createmessagesentrypoint ()
{
for (int i = 1; I <= 5; ++i)
{
Msg->setmessage (String::Concat ("M", i.ToString ());
Thread::sleep (2000);
}
Console::WriteLine ("Createmessages thread terminating");
}
};
Public ref class ProcessMessages
{
messagebuffer^ msg;
Public
ProcessMessages (messagebuffer^ m)
{
msg = m;
}
void Processmessagesentrypoint ()
{
Msg->processmessages ();
Console::WriteLine ("ProcessMessages thread terminating");
}
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.