Subj : Re: How to return a value before leaving critical section? To : comp.programming.threads From : MC Date : Wed Jul 20 2005 02:15 am >> Threading newbie here. This question has surely been answered 1000 >> times. > >> I have a member variable that I want to share between two threads. I >> make it private and I write a public accessor function, inside which, >> I use a mutex--actually, I use a Windows CRITICAL_SECTION variable and >> then call Enter/LeaveCriticalSection() but I'm hoping that's beside >> the point. The dilemna, of course, is that both statements need to be >> the last statement of the function: > >> return m_MyMember; >> *and* >> LeaveCriticalSection(m_pMyCrSection); > >> I could use an output parameter instead of a return value but then the >> calling code gets uggggglyyy! Is this the only solution? > > In C++, you have a very elegant solution where you create a 'lock >holder' class and an instance of that class. You can then have the >destructor release the lock. > > In C, why not just create a copy and return the copy? For most types, >'return' returns a copy anyway. What type is 'm_MyMember'? > > DS Yes, I'm in C++. The type is just a Windows BOOL. This discussion thread pertains to the one I previously started re: timeouts. I went with the solution that let the worker thread complete without terminating it. If the main thread detects a timeout though, I want to inform the worker not to do anything else once it comes back from its synchronous call(s). So I have a MyThread class, which wraps the thread creation, thread info and the thread function--it also has a private BOOL m_bTimeout, which the main thread can set. The worker should check that value after each synchronous call (there are a few). If the timeout flag is set, it cleans up and finishes its thread function without doing any other tasks. The thread is supposed to connect to an FTP server and upload files. So its rough algorithm is: connect() if !success || timeout then clean_up() and return change_host_dir() if !success || timeout then clean_up() and return do { upload_file() if !success || timeout then clean_up() and return } while(more_files) How do you see this code making use of a 'lock holder' class? What would the calling code look like? Thanks! Craig .