n*****g 发帖数: 178 | 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);
}
感觉这样写有点问题,求指教! |
s*****n 发帖数: 5488 | 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
|
n*****g 发帖数: 178 | 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
|
g**x 发帖数: 373 | 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()
|
n*****g 发帖数: 178 | 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
|