C#'s lock() in Managed C++ - multithreading

Does managed C++ have an equivalent to C#'s lock() and VB's SyncLock? If so, how do I use it?

C++/CLI does have a lock class. All you need to do is declare a lock variable using stack-based semantics, and it will safely exit the monitor when its destructor is called, e.g.:
#include <msclr\lock.h>
{
msclr::lock l(m_lock);
// Do work
} //destructor of lock is called (exits monitor).
m_lock declaration depends on whether you are synchronising access to an instance or static member.
To protect instance members, use this:
Object^ m_lock = gcnew Object(); // Each class instance has a private lock -
// protects instance members.
To protect static members, use this:
static Object^ m_lock = gcnew Object(); // Type has a private lock -
// protects static members.

The equivelent to a lock / SyncLock would be to use the Monitor class.
In .NET 1-3.5sp, lock(obj) does:
Monitor.Enter(obj);
try
{
// Do work
}
finally
{
Monitor.Exit(obj);
}
As of .NET 4, it will be:
bool taken = false;
try
{
Monitor.Enter(obj, ref taken);
// Do work
}
finally
{
if (taken)
{
Monitor.Exit(obj);
}
}
You could translate this to C++ by doing:
System::Object^ obj = gcnew System::Object();
Monitor::Enter(obj);
try
{
// Do work
}
finally
{
Monitor::Exit(obj);
}

There's no equivalent of the lock keyword in C++. You could do this instead:
Monitor::Enter(instanceToLock);
try
{
// Only one thread could execute this code at a time
}
finally
{
Monitor::Exit(instanceToLock);
}

Try Threading.Monitor. And catch.

Related

C++ how to change private members of managed object using a native one?

I'm working on a student project. It's a network card game. The solution contains 3 projects. Client's GUI using Windows Forms so it has managed classes. Static client's library in native C++. GUI's project has reference to it thus uses 'Mixed Rules'. Server is in native C++ as well. I use RPC middleware for communication. It works only with native C++. That is why I need the static library to hide there all the details of communication on client's side.
Since the server can at any moment change its state and that should be shown in client's GUI, I use callback approach to change Windows Forms' components. And here I found a problem because I need to change private members of managed class with the help of a native object.
There are probably different ways to do that. My idea is sending a pointer to instance of managed class into instance of native class and saving it there. So later I can call from that native object public member functions of that managed class to change components.
This is from my 'Mixed Rules' GUI project:
//Native class for changing window 'Lobby'
class LobbyI : public ClientLib::Lobby {
public:
LobbyI();
~LobbyI();
//Should change window due to current Server's state
void reDraw(const CommonLogic::ServerState&);
};
// Managed class implements GUI for window 'Lobby'
// generated by Visual Studio designer
public ref class LobbyGUI : public System::Windows::Forms::Form {
//My members
ClientLib::Mediator* mediatorPtr; // Is it correct?
LobbyI* lobbyPtr; // ?
public:
LobbyGUI(void) {
InitializeComponent();
mediatorPtr = new ClientLib::Mediator(); // Is it correct?
lobbyPtr = new LobbyI(); // ?
mediatorPtr->setCallback(lobbyPtr);
}
protected:
~LobbyGUI() {
if (components) { delete components; }
delete lobbyPtr; // Is it correct?
lobbyPtr = nullptr; // ?
delete mediatorPtr; // ?
mediatorPtr = nullptr; // ?
}
private: System::Windows::Forms::Button^ buttonLogIn;
//...
This is from native static library ClientLib:
class Lobby {
public:
virtual ~Lobby();
virtual void reDraw(const CommonLogic::ServerState&) = 0;
};
class Mediator {
CommonLogic::ServerState serverState;
Lobby* lobbyPtr;
public:
Mediator();
~Mediator();
void setCallback(Lobby* ptr) { lobbyPtr = ptr; }
void reDrawLobby() { lobbyPtr->reDraw(serverState); }
};
This code builds ok. The only thing I need now is that the member function reDraw() of native derived class LobbyI is able to change the window implemented by managed class LobbyGUI. Thus getting and keeping and using pointer to it. And then I think it all will work. How to do that?
Maybe it's not the nicest implementation in general. I would be happy to read other suggestion.
I'm also doubtful about the way I used pointers to native classes inside managed class. Is it correct? It didn't work correct until I inserted ptr=nullptr; after delete ptr; in destructor.
UPDATE: Now I see redundancy in my code. Abstract class Lobby is useless. I need only to implement reDraw() function in managed class which will have obviously access to components of the window. And then pass safe pointer to native class function which expects pointer to a function as a parameter.
Finally I've solved it!! Using this article. In the following code a native object stores provided pointer to a function of managed object. So this callback function can be invoked at any time. A delegate is used as a form of type-safe function pointer. Instance of GCHandle is used to prevent the delegate from being relocated by garbage collector.
Here is simple CLR Console Application which increments and prints some integer using callback function invoked from native object. Thus we can "change private members of managed object using a native one".
using namespace System;
using namespace System::Runtime::InteropServices;
typedef void(__stdcall *ANSWERCB)(); // define type of callback function
#pragma unmanaged
class NativeClass {
ANSWERCB cbFuncPtr = 0; // pointer to callback function
public:
void setCallback(ANSWERCB fptr) {
cbFuncPtr = fptr;
incAndPrint();
}
void incAndPrint() { cbFuncPtr(); } // invokes callback which increments and prints
};
#pragma managed
ref class ManagedClass {
public: delegate void Del();
private:
Int32 i;
NativeClass* nativePtr;
Del^ delHandle;
GCHandle gch;
public:
ManagedClass(Int32 ii) : i(ii) {
nativePtr = new NativeClass;
delHandle = gcnew Del(this, &ManagedClass::changeAndPrintInt);
gch = GCHandle::Alloc(delHandle);
IntPtr ip = Marshal::GetFunctionPointerForDelegate(delHandle);
ANSWERCB callbackPtr = static_cast<ANSWERCB>(ip.ToPointer());
nativePtr->setCallback(callbackPtr);
}
~ManagedClass() {
delete nativePtr;
nativePtr = __nullptr;
gch.Free();
}
private:
void changeAndPrintInt() // callback function
{
Console::WriteLine(++i);
}
};
int main(array<System::String ^> ^args)
{
ManagedClass mc(1);
return 0;
}

Is it possible to launch boost thread on a non static member function from other memeber function

like you probably know boost thread requires that memeber function that is fwd as argument must be static. There is a bind way to do it if it is not static, but I prefer the Object o; o.startThread() than
Object o;
boost::thread(boost::bind....) because it keeps the thread code inside the class(also exception handling).
So for example can this be rewritten to work:
class sayHello
{
string name;
public:
sayHello(string name_):name(name_)
{
}
void repeatHello()
{
while (true)
{
boost::this_thread::sleep(posix_time::seconds(3));
cout<<"Hello "<<name<<endl;
}
}
void infiniteRun()
{
boost::thread thr(repeatHello);//broken line
}
};
P.S. for people wandering what is the "bind way" AFAIK it is this:
sayHello sh("world");
boost::thread thr(boost::bind(&sayHello::repeatHello,&sh));
Yes...
void infiniteRun()
{
boost::thread thr(boost::bind(&sayHello::repeatHello,this));
}
Although doing it that way fraught with danger of memory leaks and access violations. When dealing with threads, I would highly recommend using smart pointers to keep things alive correctly.

how to create a thread using a non static method in vc++ mfc

I am creating a thread using this call:
m_pThread=AfxBeginThread(read_data,(LPVOID)hSerial);
read_data is a static method in my class.
But I want to call a non static method and make a thread.
As I want to share a variable between this thread and one of my class method.
I tried taking a static variable but it gave some errors.
You cannot create a thread using a non-static member of a function as the thread procedure: the reason is all non-static methods of a class have an implicit first argument, this is pointer this.
This
class foo
{
void dosomething();
};
is actually
class foo
{
void dosomething(foo* this);
};
Because of that, the function signature does not match the one you need for the thread procedure. You can use a static method as thread procedure and pass the this pointer to it. Here is an example:
class foo
{
CWindThread* m_pThread;
HANDLE hSerial;
static UINT MyThreadProc(LPVOID pData);
void Start();
};
void foo::Start()
{
m_pThread=AfxBeginThread(MyThreadProc,(LPVOID)this);
}
UINT foo::MyThreadProc(LPVOID pData)
{
foo* self = (foo*)pData;
// now you can use self as it was this
ReadFile(self->hSerial, ...);
return 0;
}
I won't repeat what Marius said, but will add that I use the following:
class foo
{
CWindThread* m_pThread;
HANDLE hSerial;
static UINT _threadProc(LPVOID pData);
UINT MemberThreadProc();
void Start();
};
void foo::Start()
{
m_pThread=AfxBeginThread(_threadProc,(LPVOID)this);
}
UINT foo::MyThreadProc(LPVOID pData)
{
foo* self = (foo*)pData;
// call class instance member
return self->MemberThreadProc();
}
UINT foo::MemberThreadProc()
{
// do work
ReadFile(hSerial, ...);
return 0;
}
I follow this pattern every time I use threads in classes in MFC apps. That way I have the convenience of having all the members like I am in the class itself.

Threading from within a class with static and non-static methods

Let's say I have
class classA {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
class classB {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
static void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?
Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB?
Does again the static really change nothing in this case?
Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.
In this case there is no functional difference. Each thread gets it's own stack
Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.
Each thread would get it's own stack. There is no functional difference that I can tell between the two.
The only difference (obviously) is that the static version would be unable to access member functions/variables.

Is this a thread safe way to initialize a [ThreadStatic]?

[ThreadStatic]
private static Foo _foo;
public static Foo CurrentFoo {
get {
if (_foo == null) {
_foo = new Foo();
}
return _foo;
}
}
Is the previous code thread safe? Or do we need to lock the method?
If its ThreadStatic there's one copy per thread. So, by definition, its thread safe.
This blog has some good info on ThreadStatic.
A [ThreadStatic] is compiler/language magic for thread local storage. In other words, it is bound to the thread, so even if there is a context switch it doesn't matter because no other thread can access it directly.

Resources