Can someone Explain Mutex and how it is used?

前端 未结 4 1183
天涯浪人
天涯浪人 2021-01-12 10:01

I read a few documents about Mutex and still the only Idea I have got is that it helps preventing threads from accessing a resource that is already being used by another res

相关标签:
4条回答
  • 2021-01-12 10:47

    This link in msdn provides a similar example as yours with threads made in the main() function. But again the shared resource, which is supposed to be a database is not included.
    Anyway, a shared resource is whatever that needs to be accessed from multiple threads: settingsfiles, drivers, database,...

    Mind you that the counter in the example is written while protected by the mutex, while it is been read while not being protected. While in this case, there is probably no problem, it is a bit sloppy.

    0 讨论(0)
  • 2021-01-12 10:50

    You can refer this SO post for comparison of various thread synchronization mechanisms Difference between Locks, Mutex and Critical Sections

    If you want specific information Mutex then wikipedia will give you enough details.

    0 讨论(0)
  • 2021-01-12 10:57

    Maybe It will be the best source to you

    http://en.wikipedia.org/wiki/Mutual_exclusion

    0 讨论(0)
  • 2021-01-12 11:05

    A mutex provides mutually exclusive access to a resource; in your case, a database. There aren't multiple threads in your program, but you can have multiple instances of your program running, which is what your mutex is protecting against. Effectively, it is still protecting against access from more than one thread, it's just that those threads can be in separate processes.

    Your code is creating a named mutex that can be shared across multiple instances of your application. This is a form of interprocess communication. MSDN documentation on CreateMutex has additional helpful information about named mutexes:

    Two or more processes can call CreateMutex to create the same named mutex. The first process actually creates the mutex, and subsequent processes with sufficient access rights simply open a handle to the existing mutex...

    Multiple processes can have handles of the same mutex object, enabling use of the object for interprocess synchronization.

    A mutex is only necessary here if the database you're working against doesn't inherently support multithreaded access.

    0 讨论(0)
提交回复
热议问题