问题是关于编码风格。如何创建面向外部但能很好地处理锁定的功能。
void Timer_start(Timer *t){ //this is a user facing function
if (t->state == Timer_paused){
Timer_resume(t);
} else {
Timer_initialize(t);
}
}
void Timer_resume(Timer *t){ //this is also a user facing function
Lock_acquire(t->lock);
//...do work
Lock_release(t->lock);
}
void Timer_initialize(Timer *t){ //and so is this
//...do work (just to illustrate the the functions arent necessarily simply wrapped with the locking functions)
Lock_acquire(t->lock);
//...do work
Lock_release(t->lock);
}
在示例中,Timer_start
应该像其他两个函数一样包裹在Lock_acquire
其中,Lock_release
因为在状态检查后可能会立即被中断。问题是我无法将函数包装在正确的锁定函数中,因为被调用的函数本身会获取锁定。是否有一种编码风格可以很好地处理这个问题?