• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2052
  • Last Modified:

Mutex, lock, wait, notify mechanism

I am reading a lot of material but still not sure how it works.  Question is about Boost threads or C++11 threads.

When a critical section is locked with scoped_lock (unique_lock) or lock_guard and suppose another thread tried to lock it while it is still locked, will the second thread go to sleep state ?  And will it go to read state immediately after lock is released (first thread goes out of scope)?

Now if multiple threads try to lock an already locked thread, do they all go to sleep state? And when the lock is released, which one of the waiting threads go to ready state?  All of them?

Why do we need notify_one?  To wake up the first thread?  Is there a queue of waiting threads?

Some sample code to do it efficiently would help.
0
farzanj
Asked:
farzanj
  • 2
  • 2
2 Solutions
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Correct.  The second thread will go to sleep and then wake up when the first releases the lock.

For multiple threads, all will go to sleep.  Which one wakes up, though, is unspecified!  In other words, you can't rely on any specific ordering in the way they are woken up in turn.

See "Scheduling Policies":
http://www.boost.org/doc/libs/1_33_1/doc/html/threads/concepts.html#threads.concepts.FIFO-scheduling-policy

    "In order to ensure portability, all Boost.Threads mutex objects use an unspecified scheduling policy."

This can lead to "thread starvation":
http://en.wikipedia.org/wiki/Thread_starvation
http://en.wikipedia.org/wiki/Dining_philosophers_problem

In a nutshell, if you find this is a possibility for your current implementation, then you need to re-design your system with a more sophisticated scheduling algorithm.
0
 
farzanjAuthor Commented:
I am on it, I apologize for the delay but I was detained by some other priorities.  I need some more clarifications.  For instance:
If sleeping threads are rescheduled by themselves, why do we need notify and notify_all?
How do you do FIFO scheduling?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
notify tells the waiting thread(s) that some condition has been met, so they can wake up.  It is undefined, though, which waiting thread will actually get the lock and execute though.  If you notify_all, only one will actually acquire the lock at a time.

This one is a good read:
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
0
 
farzanjAuthor Commented:
Thank you!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now