Redian新闻
>
求教三进程间同步的问题,原题是CC150第5版的16.5
avatar
求教三进程间同步的问题,原题是CC150第5版的16.5# JobHunting - 待字闺中
n*g
1
题目是CC150第五版16.5题,题目是这样的:
Suppose we have the following code:
public class Foo {
public Foo() { . . . }
public void first() { ... }
public void second() { ... }
public void thirdQ { ... }
The same instance of Foo will be passed to three different threads. ThreadA
will call first, threads will call second, and threadC will call third.
Design a mechanism to ensure that first is called before second and second
is called before third.
这要换成C语言来问的话,是不是等同于这样问:一个foo函数,确保foo先被first调用
,然后再被second和third调用(first,second,和third来自不同的thread)?
如果等同话 ,用C语言,Semaphore如何解答呢?
我的想法是:
void first()
{
signal(sem1);
}
void second()
{
wait(sem1);
signal(sem2);
}
void third()
{
wait(sem2);
}
感觉这样写有点问题,求指教!
avatar
s*n
2
有什么问题?semiphore太heavy了吧。不如用condition variable.

ThreadA

【在 n*****g 的大作中提到】
: 题目是CC150第五版16.5题,题目是这样的:
: Suppose we have the following code:
: public class Foo {
: public Foo() { . . . }
: public void first() { ... }
: public void second() { ... }
: public void thirdQ { ... }
: The same instance of Foo will be passed to three different threads. ThreadA
: will call first, threads will call second, and threadC will call third.
: Design a mechanism to ensure that first is called before second and second

avatar
n*g
3

貌似我搞混了,这里我用wait和signal其实就是想用condition variable。
不过cond应该和mutex一起用吧?我觉得应该这么写,不知道有没问题:
void first()
{
lock();
signal(second);
unlock();
}
void second()
{
lock();
wait(first);
unlock();
lock();
signal(third);
unlock();
}
void third()
{
lock();
wait(second);
unlock();
}

【在 s*****n 的大作中提到】
: 有什么问题?semiphore太heavy了吧。不如用condition variable.
:
: ThreadA

avatar
g*x
4
int i=0;
mutex m;
cond c;
void first() {
{
lock(m);
i++;
signal(c);
unlock(m);
}
void second() {
lock(m);
while (i!=1) {
wait(m, c);
}
i++;
signal(c);
unlock(m);
}
void third() {
lock(m);
while (i!=2) {
wait(m,c);
}
//...
unlock(m);
}

【在 n*****g 的大作中提到】
:
: 貌似我搞混了,这里我用wait和signal其实就是想用condition variable。
: 不过cond应该和mutex一起用吧?我觉得应该这么写,不知道有没问题:
: void first()
: {
: lock();
: signal(second);
: unlock();
: }
: void second()

avatar
n*g
5

ThreadA
不知道三楼的对吗?

【在 n*****g 的大作中提到】
: 题目是CC150第五版16.5题,题目是这样的:
: Suppose we have the following code:
: public class Foo {
: public Foo() { . . . }
: public void first() { ... }
: public void second() { ... }
: public void thirdQ { ... }
: The same instance of Foo will be passed to three different threads. ThreadA
: will call first, threads will call second, and threadC will call third.
: Design a mechanism to ensure that first is called before second and second

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。