TIP: Click on subject to list as thread! ANSI
echo: os2prog
to: Phil Crown
from: Mario Semo
date: 1996-11-08 09:07:36
subject: Mutex semaphores

Hallo Phil!

Antwort auf eine Message von Phil Crown an All:

 PC> Is this the proper way to use a Mutex Semaphore to protect a resource?


 PC> ULONG  someFn()
 PC> {

 PC>   request.MutexSem();

 PC>   ULONG rc = 0;

 PC>   rc = something;

 PC>   str = somethingtoo;  // this also needs protecting because str is
                      
 PC> // used in another function that is also                        //
 PC> called by two or more threads.

 PC>   release.MutexSem();

 PC>   return rc;  // A calling thread is pre-empted here before returning
 PC> rc.

 PC>               // A second threads comes along and completes the
 PC>               // function before the first thread has finished,
 PC>               // thus causing rc to contain invalid data.
 PC>               // Is this possible?
 PC> }

a) it is possible that the first thread is preempted immediate after the
mutex.releease
b) it is NO problem. because RC is a local STACK based variable, and both
threads have different stacks. you only need to protect against GLOBAL
data. not against local stack based data
c) another trick for using mutex-sema4 in C++ code. sample:

     mutex.request();
     call someones();
     mutex.release();
     return rc;

 now - what if someone() is throwing an exception? you caller will (maybe)
catch the exception and handle it, but the mutex is still locked!!! 

 so (better):

   class RequestMutex
   {
    public:
       RequestMutex(Mutex & mutex) : mutex(mutex) { mutex.request();}
       ~RequestMutex() { mutex.release();}
    private:
       Mutex mutex;
   };

 function()
 {
  RequestMutex request(mutex);
  call someone();
  return rc;
 };

 now, request is a local object, and when an exception is thrown, ALL local
(stack based) objects get destroyed! so, ~RequestMutex is called and the
sema4 is released. 

Servus, Mario!

--- FleetStreet 1.18 PR#2
* Origin: LC/32 Development Team, KirchnerSoft, Vienna, Austria (2:310/14.11)
SEEN-BY: 50/99 270/101 620/243 625/160 711/401 409 410 413 430 808 809 934
SEEN-BY: 711/955 712/407 515 624 628 713/317 800/1
@PATH: 310/14 1 24/999 888 396/1 270/101 712/515 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.