2.假设有2个螺纹T1,T2。请描述以下解决方案是否为满足三个条件的临界部分提供了正确的同步:相互排除,有限的等待和进步。
T1 |
T2 |
共享:int t1inside = 0,t2inside = 0; |
而(1){ 而(t2inside); t1inside = 1; // critical section t1inside = 0; } |
而(1){ 而(t1inside); t2inside = 2; // critical section t2inside = 0; } |
3.请为以下问题写伪代码:
Consider a pizza store which has 10 seats. A customer come to buy pizza. If there is any unsold pizza left in the kitchen, he can get it immediately. If not, (s)he need wait for chef to make one. After the customer gets the pizza, (s)he will grab a seat and start eating. If there is no seat, (s)he needs to wait. When (s)he finishes eating, (s)h will left the store. The chef in the kitchen just keeps making pizza. However, (s)he stops if there are 5 unsold pizza left in the kitchen. If a customer come to buy one, (s)he resumes the work to make new pizza. Please write pseudocode for both customer and chef using信号to solve this problem, and synchronize chef and customers.
4.编写一个多线程程序来解决生产者和消费者问题。
- There are two types of worker thread: producer and consumer. A producer thread randomly generate an integer between 0-100 (You can use random()/srandom() or drand48()/srand48() to generate random number in C), and put it into the buffer. A consumer thread simple take the first integer from the buffer. A circular arrayshould be used for the buffer. You do not need loop for both types of thread.
- 假设工作人员总数为20,缓冲区大小为10。您的程序应随机生成生产者和消费者的数量。他们的关系应为:num_producers + num_consumers = num_threads,num_producer -num_consumer <= buffer_size,num_consumer <= num_produducer,因此不会永远阻止线程。消费者和生产者线程之间的顺序应是任意的。例如,您不得生成所有生产者(消费者),然后生成所有消费者(生产者)。(5分)
- 同步生产商和消费者。
- You can choose any type of language (e.g. C/C++/Java) to implement this program. Your output will look like the following:
生产者数量:12消费者数量:8
Thread 0 produce 63 in buffer 0, current number of items is 1
Thread 1 consume item 63 in buffer 0, current number of items is 0
线程3在缓冲区1中产生45,目前的项目数为1
线程5在缓冲区2中产生88,目前的项目数为2
线程4在缓冲区1中消耗项目45,当前项目数为0
........
..... .....
......
There are still 4 items left in the buffer: 96,26,52,81
- Please check blackboard for more reference about pthread library if you choose to use it.
You can choose any of the following questions:
5. Write a program to simulate pizza store problem in problem 3.
描述如何在Linux内核中实现Spinlock,以及如何/在何处使用?请举一些具体的例子,例如列出与Spinlock实现有关的数据结构/功能,描述某些Spinlock函数的代码,描述如何将这些函数用于同步,列出使用的功能。