开发者

using mutexes in external modules

If I have a module that has a mutex and I write the value of an int variable using lock/unlock on the mutex, how is the same mutex locked/unlocked in anothe开发者_高级运维r module that is being run in a thread?

The external module also needs to write the value of the variable and this is being done in a threaded loop function. How does one lock this using the same mutex or should another mutex be used?

What happens if 2 different mutexes lock the same memory segments(not necessarily simultaneously)?


In order to share a mutex using pthreads, you are going to have to somehow share the address of the mutex through a pointer or make the mutex a globally accessible variable.

Mutexes or semaphores themselves do not lock a given memory or critical code section ... instead they lock access to a specific "flag" or location in memory (i.e., like an unsigned long or some other POD type) that is then used to determine access to a critical section or other globally accessible memory location. In other words once a thread "owns" a given mutex, it gets to have access to a segment of code or memory section that any other thread trying to obtain ownership of that same mutex is blocked from for the duration of the owning thread's lock.

If you use two different mutexes to block access to a given location, that does not provide mutually exclusive access to the actual memory segment ... each thread that does not share a mutex will have equal access to the memory segment even though they may each have an ownership lock on their respective mutexes. Therefore the memory segment is not really protected ... two threads could access the memory segment at the same time, creating concurrency issues.

So again, if you have different modules or threads, and you want to have exclusive access to a given section of code or memory, you're going to have to share the same mutex between those elements. There are many ways this could be done, either though something like named semaphores if you need to-do this for multiple separate processes, or through a shared memory segment (i.e., shmget(), shmat(), shmdt, etc.), etc. if you can't somehow share a globally accessible mutex or pointer because of some separation of address space between your modules.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜