Multi Threads... just a simple example plz...

Started by
14 comments, last by crakinshot 21 years, 7 months ago

here
Advertisement
quote:Original post by mutex
CCriticalSection g_cs;CString g_sData;  // data that requires synchronizationUINT ThreadOne(LPVOID param){  g_cs.Lock();  sData = "Blah";  g_cs.Unlock();  return 0;}  


If unluckily sData got sick and throws an exception, your g_cs won''t be unlocked... and you will have some ''deadlock'', resulting ThreadTwo waiting......
"after many years of singularity, i'm still searching on the event horizon"
quote:If unluckily sData got sick and throws an exception, your g_cs won't be unlocked... and you will have some 'deadlock', resulting ThreadTwo waiting......


Good point!

The typical solution is to write a guard class that will automatically lock and unlock the critical section for you.


    class CGuard{  CCriticalSection& cs;public:   CGuard (CCriticalSection& cs) : cs (cs) { cs.  Lock (); }  ~CGuard (CCriticalSection& cs)           { cs.Unlock (); }};CCriticalSection g_cs;CString g_sData;  // data that requires synchronizationUINT ThreadOne(LPVOID param){  CGuard MyGuard (g_cs);  sData = "Blah";  return 0;}  



Remember that CGuard will synchronize access to your whole function, which is probably not ideal. Normally, you should only synchronize access to the data and spend as little time within the synchronized section. After all you wish these threads to run asynchronously, right?

Here's how:



  UINT ThreadOne(LPVOID param){  // <insert code to do other stuff>  {    CGuard MyGuard (g_cs); // <- it is locked here    sData = "Blah";  } // <- it is unlocked here  // <insert code to do other stuff>  return 0;}    


Although I thought that it was not a good idea to throw into system code (e.g., out of a thread function, out of a window function, etc.). If you use exceptions, you should do this to catch any exceptions that might be thrown out of the thread function:


  UINT ThreadOne(LPVOID param){  try  {    // <insert code to do other stuff>    {      CGuard MyGuard (g_cs);      sData = "Blah";    }    // <insert code to do other stuff>  }  catch (...)  {    // <insert code to handle exception>  }  return 0;}  



[edited by - null_pointer on September 11, 2002 9:35:08 AM]
Boost.Threads

daerid@gmail.com
cool thx guys... I''ll look over all this and get it going....

thanks for all your help...
-=CrAKiN:ShOt=-I could put something witty here but I'm not that stupid...
In DELPHI...using mul. threads is soooooooo easy & safe...
______________________________Only dead fish go with the main-stream.

This topic is closed to new replies.

Advertisement