Pthread Queue System
I'm working on my assignment on pthreads. I'm new and never touched on pthreads before. Is there any sample codes or resources out there that anyone of you have, that might aid me in my assignment?
Here are my assignment details. A pthread program about queue system:
Write a C/C++ Pthread program for a Dental clinic’s queuing system that declares an array of integers of size N, where N is the maximum number of queue for the day. The pthread program uses two threads.
Whenever there is a new dental appointment, the first thread (the creator) puts the queue numbers in the array, one after the other. The second thread (the remover) removes the 开发者_开发技巧queue numbers from the array whenever the dentist has seen the patient. This is done in a FIFO fashion (First In First Out). The algorithm of the creator is as follows:
• If the array is not full then put a new number in it (the numbers start at 1 and are incremented by one each time, so the creator create queue number 1, 2, 3 etc.)
• sleep for 1 to 10 seconds, randomly
• repeat
The algorithm of the remover is as follows:
• If the array is not empty then remove its smallest queue number.
• sleep for 1 to 10 seconds, randomly
• repeat
You should use mutex locks to protect things that must be protected. Each thread should print on the screen what it is doing (eg: "number 13 is added into the queue", "number 7 is removed from the queue", etc.). The program should run forever.
Any help will be appreciated. Thanks.
For generally starting out with pthreads, this is a good website with possibly more info than you need (but I like detail). It runs through a lot of the basics for pthreads and more. If you prefer a dead-tree tutorial, this book is pretty good and gives you a good grounding in most of the features of the Linux API, or the core libraries, if you want to call it that. This stackoverflow question deals with mutexes vs semaphores pretty concisely.
Finally, I like this site for its converage of Linux Threading and Synchronisation.
Hopefully these give you some reading material. Work out how you handle threads, then how you synchronise them, then attack your problem.
This is the classic producer-consumer problem.
There are many ways to solve this, but the easiest thing is to have one lock on a queue, and when you add or remove an item from it, in the producer or consumer, respectively, lock the queue, do the work, and then unlock the queue. In the consumer, process the item, and in the producer, go on to the work of getting a new item.
You may wish to lay out your data structures, and then define locks, describing specifically what the lock locks, so you are sure all your data that both threads access stays synchronized.
Thanks for tagging this as homework; I hope this gets you started in the right direction. You may also wish to lock around things like printing to the console to ensure that these operations don't overlap.
精彩评论