pengsenl
October 15th, 2005, 03:49 AM
now i use several threads to wite a serial port ,i want only one thread to write the port at the same time ,I don't know how to do it . i hope some one help me soon
|
Click to See Complete Forum and Search --> : a question about multiplethread pengsenl October 15th, 2005, 03:49 AM now i use several threads to wite a serial port ,i want only one thread to write the port at the same time ,I don't know how to do it . i hope some one help me soon Vanaj October 15th, 2005, 04:23 AM Take a look at Mutex's and Critical Sections. Siddhartha October 15th, 2005, 05:32 AM [ redirected ] Regards, Siddhartha Siddhartha October 15th, 2005, 05:40 AM The easiest approach to restricting the number of threads that execute a piece of code to one is via Critical Sections. Critical Section Objects (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/critical_section_objects.asp) One works with Critical Sections using Win APIs - InitializeCriticalSection (http://msdn.microsoft.com/library/en-us/dllproc/base/initializecriticalsection.asp) EnterCriticalSection (http://msdn.microsoft.com/library/en-us/dllproc/base/entercriticalsection.asp) LeaveCriticalSection (http://msdn.microsoft.com/library/en-us/dllproc/base/leavecriticalsection.asp) DeleteCriticalSection (http://msdn.microsoft.com/library/en-us/dllproc/base/deletecriticalsection.asp) Sample: Using Critical Sections (http://msdn.microsoft.com/library/en-us/dllproc/base/using_critical_section_objects.asp) So, in your case, the code would be something like this - Creating and Initializing: // A global object, or a globally accessible object (like static member) CRITICAL_SECTION myCS; // In the main thread ::InitializeCriticalSection (&myCS); Using Critical Sections: // Inside the worker thread // At the point in code that needs to be protected // And needs to be entered one thread at a time ::EnterCriticalSection (&myCS); // The lines of code that need to be protected ::LeaveCriticalSection (&myCS); Finally, Deleting: // Again in the main thread, after the worker threads // Have ended and the CS is not needed ::DeleteCriticalSection (&myCS); Hope, you now have a clear idea of the way to proceed. codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |