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
Printable View
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
Take a look at Mutex's and Critical Sections.
[ redirected ]
Regards,
Siddhartha
The easiest approach to restricting the number of threads that execute a piece of code to one is via Critical Sections.
One works with Critical Sections using Win APIs -
So, in your case, the code would be something like this -
Creating and Initializing:
Using Critical Sections:Code:// A global object, or a globally accessible object (like static member)
CRITICAL_SECTION myCS;
// In the main thread
::InitializeCriticalSection (&myCS);
Finally, Deleting:Code:// 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);
Hope, you now have a clear idea of the way to proceed.Code:// Again in the main thread, after the worker threads
// Have ended and the CS is not needed
::DeleteCriticalSection (&myCS);