EasyLogger
EasyLogger copied to clipboard
A potential data race problem 一个潜在的数据竞争问题
void elog_async_output(uint8_t level, const char *log, size_t size) {
/* this function must be implement by user when ELOG_ASYNC_OUTPUT_USING_PTHREAD is not defined */
extern void elog_async_output_notice(void);
size_t put_size;
if (is_enabled) {
if (level >= OUTPUT_LVL) {
put_size = async_put_log(log, size);
/* notify output log thread */
if (put_size > 0) {
elog_async_output_notice();
}
} else {
elog_port_output(log, size);
}
} else {
elog_port_output(log, size);
}
}
对于上述函数,如果混合输出不同级别的日志,将会出现两个线程操作一个日志文件的的场景,容易出现数据竞争。有两种修改方法:1,开启异步输出后,所有的日志全部异步输出。2,在文件操作上加锁。 For the above function, if you output different levels of log , there will be two threads operating on a log file , which will lead to data race easily. There are two ways to modify this: 1. When asynchronous output mode is turned on, all logs are output asynchronously. 2, lock the file when operate it.
进一步阅读源码,可以看到elog_file_write中有加锁操作elog_file_port_lock。该操作在linux下已被实现,在Windows环境下未被实现。 我在有空会添加这部分实现。预计采用互斥锁这一方法。