假设我喜欢:
static int write_log = 0;
void *logger__run(void *arg){
// logger thread execution.
while(1){
// get log message from shared queue.
if(write_log){
// just checking write_log value.
// write logs till write_log is true.
}
// destroy log message.
}
}
void logger__set_logging(int p_write_log){
// other threads can start / stop logging by logger thread.
// just assigning value.
write_log = p_write_log;
}
int logger__is_logging(void){
// other threads can check whether logger thread is logging or not.
// just returning value.
return write_log;
}
函数logger__run()将由记录器线程执行.其他线程可以通过设置write_log共享变量来启动/停止记录器线程的日志记录.其他线程也可以检查记录器是否正在记录.
如您所见,只有单个语句,如:赋值或返回值或在循环中检入.那么,我们是否需要使用锁来保护此write_log访问权限?
最佳答案 我会说是的. logger__run可能会为write_log读取一个不正确的值,因为logger__set_logging中的赋值不是原子的(因此,int值的某些字节可能已被写入,而其他字节可能尚未进入此单一赋值).