正确同步 C++代码
前段时间有人问我一个问题,我不确定如何回答,问题如下:任何人都可以告诉我我应该如何使用 C++
编写代码来帮助同步教授和他的/她的学生在办公时间。如果周围没有学生提问,教授当然想小睡一会儿;如果有学生想提问,他们之间必须同步并与教授同步,以便 任何时候只有一个人在说话, 每个学生的问题都由教授回答,并且 在教授回答完前一个问题之前,没有学生会问另一个问题。 您将编写四个过程:AnswerStart()、AnswerDone()、QuestionStart() 和 QuestionDone()。 教授循环运行代码:AnswerStart();给出答案;回答完成()。在提出问题之前,AnswerStart 不会返回。每个学生循环运行代码:QuestionStart();提出问题;问题完成()。 QuestionStart() 在轮到学生提问之前不会返回。由于教授认为学生不等待答案是不礼貌的,因此在教授回答完问题之前,QuestionEnd() 不应返回。
I was given a question some time ago that I am not sure of how to answer, the question is typed below: can anyone give me an idea of how i should go about doing this using C++
write code to help synchronize a professor and his/her students during office hours. The professor, of course, wants to take a nap if no students are around to ask questions; if there are students who want to ask questions, they must synchronize with each other and with the professor so that
only one person is speaking at any one time,
each student question is answered by the professor, and
no student asks another question before the professor is done answering the previous one.
You are to write four procedures: AnswerStart(), AnswerDone(), QuestionStart() , and QuestionDone().
The professor loops running the code: AnswerStart(); give answer; AnswerDone(). AnswerStart doesn't return until a question has been asked. Each student loops running the code: QuestionStart(); ask question; QuestionDone(). QuestionStart() does not return until it is the student's turn to ask a question. Since professors consider it rude for a student not to wait for an answer, QuestionEnd() should not return until the professor has finished answering the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
读者/作者锁可能就是您正在寻找的。
根据社区指南,这听起来像是一个家庭作业问题你能让我们知道你尝试过什么吗?
Readers/Writer locks might be what you are looking for.
This sounds like a homework question, as per the community guidelines can you let us know what you've tried?
我假设这是一项课堂作业,所以我不会泄露答案。
我会用一个活动对象来处理这个问题。
I am assuming this is a class assignment so I won't give away the answer.
I would handle this with an active object.
您将必须对变量进行序列化访问并使用锁来确保不会同时发生多个操作。本文档的第一部分解释了如何在 C++ 中使用锁。希望这能为您指明正确的方向。
http://www.cs.utexas.edu/ 〜薰衣草/课程/cs371/lectures/lecture-10.pdf
you are going to have to have serialized access to variables and use locks to make sure multiple actions are not happening at once. The first part of this document explains how to use locks in c++. Hopefully that will point you in the right direction.
http://www.cs.utexas.edu/~lavender/courses/cs371/lectures/lecture-10.pdf