How to make a function thread safe in mc++?

G

Guest

Greetings,

I was looking at the C#'s "lock()" statement, and I was wondering if there
was an equivalent or recommended way of doing this in MC++.

I have a thread which I am calling a function from mc++, and I was wondering
what
the recommended ways of making it thread safe within the mc++ world.

Thanks in advance for any suggestions.
 
G

Guest

Right after I made the post I stumbled accross something that I could use for
thread safety, so I thought I would post in case someone else needs it for a
solution.

Solution:
void Foo()
{
// At the beginning of your function.
System::Threading::Monitor::Enter(this);

.... Do some code work

// Add the end of your function (this has to be called)
System::Threading::Monitor::Exit(this);
}
 
C

Carl Daniel [VC++ MVP]

BartMan said:
Right after I made the post I stumbled accross something that I could
use for thread safety, so I thought I would post in case someone else
needs it for a solution.

Solution:
void Foo()
{
// At the beginning of your function.
System::Threading::Monitor::Enter(this);

... Do some code work

// Add the end of your function (this has to be called)
System::Threading::Monitor::Exit(this);
}

That's precisely what the C# 'lock' construct does.

-cd
 
N

Nemanja Trifunovic

I think it would be pretty easy to wrap this into a RAII __nogc class
with a little help from gcroot.
 
G

Guest

Hello Nemanja,

Thanks for the great idea, I didn't know about gcroot which is really
usefull. :)
Here is my attempt.

public __gc class lock
{
public:
lock(System::Object* obj)
{
threadObject = obj;
System::Threading::Monitor::Enter(threadObject);
}
~lock()
{
System::Threading::Monitor::Exit(threadObject);
}
protected:
gcroot<System::Object*> threadObject;
};
 
J

Jochen Kalmbach [MVP]

Hi Carl!
That's precisely what the C# 'lock' construct does.

Almost... the C# also does an try-finally construct..

System::Threading::Monitor::Enter(this);
__try
{
// Do some code work
}
__finally
{
System::Threading::Monitor::Exit(this);
}

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top