1

I have a class with 2 methods say, Connect and Disconnect. Now when i call class B i get an address for A using that i'll connect and once it is done i have to call class C to perform disconnect operation on that same address.

I can achieve this if I make A *a as a global variable. But when it comes to multithreading and A being global uses only one address/instance and it disconnects before other threads were running causing access violation exception.

How to resolve this? Thanks in advance.

class A()
{
Connect();
Disconnect();
};
A *a = nullptr;

class B()
{
 a = new A(); 
 a->Connect();
}

class C()
{
 if(!a)
   a->Disconnect();
}
Edwin Vivek N
  • 564
  • 8
  • 28

2 Answers2

0

At first your if condition in class c is incorrect. It should be if(a). Because if a variable has null value then it can pass your if condition and you want to call disconnect method of null variabe. Second you should consider to run class c thread after class b thread.

hamed
  • 471
  • 1
  • 9
  • 22
0

How about protecting any access to a with a lock, at least it would avoid problems with the state of a when multi threading.

http://www.cplusplus.com/reference/mutex/mutex/lock/

If you cannot use because of c++Cli restrictions try use with an gcroot lockingHandle

Or use magic statics. But be aware, if the A class access any .NET resources and get destructed at the end of the application, while cleaning up those statics, then it will end in an crash, or at least could lead to not freed ressources.

Is publishing of magic statics thread safe?

I used a lock in the beginning, but later i could change to other ways and not longer be dependent on a static global object.

JackGrinningCat
  • 480
  • 4
  • 9
  • I think mutex lock cannot be used in clr project. – Edwin Vivek N Feb 08 '18 at 04:33
  • @EdwinVivekN That's right, you cannot include a mutex in a file that is build with /clr I posted [here](https://stackoverflow.com/a/48589063/9293869) an example, the corresponding implementation cpp is compiled without /clr. Generally called Pimpl-Ideom. Or you can look for this documentation about lock with an gc-handle [msclr lock](https://msdn.microsoft.com/en-us/library/sy1y3y1t.aspx) – JackGrinningCat Feb 08 '18 at 12:34
  • @EdwinVivekN Di you get the idea? – JackGrinningCat Feb 09 '18 at 12:40
  • https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3814789-support-c-11-concurrency-header-files-in-c-cli – JackGrinningCat Feb 09 '18 at 16:04