题目描述
给你一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
思路:用互斥锁或者信息量等方法都可以实现。
题解:
方法一(信息量的方法):主要就是信息量的释放sem_post和等待函数sem_wait的使用
typedef struct {
// User defined data may be declared here.
sem_t t1,t2;
} Foo;
Foo* fooCreate() {
Foo* obj = (Foo*) malloc(sizeof(Foo));
sem_init(&obj->t1,0,0);
sem_init(&obj->t2,0,0);
// Initialize user defined data here.
return obj;
}
void first(Foo* obj) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
sem_post(&obj->t1);
}
void second(Foo* obj) {
sem_wait(&obj->t1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
sem_post(&obj->t2);
}
void third(Foo* obj) {
sem_wait(&obj->t2);
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
void fooFree(Foo* obj) {
// User defined data may be cleaned up here.
free(obj);
}
方法二(互斥锁法):主要是开锁关锁的问题,实际上和信息量法差不多;
typedef struct {
// User defined data may be declared here.
pthread_mutex_t t1,t2;
} Foo;
Foo* fooCreate() {
Foo* obj = (Foo*) malloc(sizeof(Foo));
// Initialize user defined data here.
pthread_mutex_init(&obj->t1,NULL);
pthread_mutex_init(&obj->t2,NULL);
pthread_mutex_lock(&obj->t1);
pthread_mutex_lock(&obj->t2);
return obj;
}
void first(Foo* obj) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
pthread_mutex_unlock(&obj->t1);
}
void second(Foo* obj) {
pthread_mutex_lock(&obj->t1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
pthread_mutex_unlock(&obj->t2);
}
void third(Foo* obj) {
pthread_mutex_lock(&obj->t2);
pthread_mutex_unlock(&obj->t1);
// printThird() outputs "third". Do not change or remove this line.
printThird();
pthread_mutex_lock(&obj->t1);
}
void fooFree(Foo* obj) {
// User defined data may be cleaned up here.
pthread_mutex_destroy(&obj->t1);
pthread_mutex_destroy(&obj->t2);
free(obj);
}