Misuse of windows mutex

Source: Internet
Author: User

The purpose is as follows:
There are two threads A and B. A waits for an event in thread B in A loop. For example, in A network application, A is the main thread, and B is the receiving thread. A sends A request to the server,
Then, wait for the server to return A response or send the response again after timeout. When B receives the response, it notifies.
First look at the following code:

Int main () {HANDLE hMutex = CreateMutex (NULL, FALSE, NULL); WaitForSingleObject (hMutex, INFINITE); return 0 ;}

WaitForSingleObject always returns immediately. Why does WaitForSingleObject not work ??
It turns out that I understood it wrong and set a low-level error. WaitForSingleObject should have been returned immediately.
The first line creates an anonymous mutex. At the beginning, no thread has the mutex, so WaitForSingleObject (hMutex, INFINITE)
Always returns immediately. If WaitForSingleObject (hMutex, INFINITE) is called in thread B)
Previously, WaitForSingleObject (hMutex, INFINITE) in thread A will not return.

A single thread is always executed sequentially, So synchronization and mutex are not required. Synchronization and mutex always involve two or more threads.
I should have used semaphores or events ......

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.