Mutex lock threads

前端 未结 4 1541
逝去的感伤
逝去的感伤 2020-12-13 04:15

Am new to multi threaded/processs programming. So here\'s what I need to clarify.

Process A code

pthread_mutex_lock()
    pthread_create(fooAPI(share         


        
4条回答
  •  情深已故
    2020-12-13 04:46

    Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)

    Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.

    Both processes should basically do the same thing when accessing the mutex.
    lock() If the lock succeeds, then { access sharedResource unlock() }

    Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ

提交回复
热议问题