diff --git a/nemu/src/device/audio.c b/nemu/src/device/audio.c index 16cf7bf..64f5977 100644 --- a/nemu/src/device/audio.c +++ b/nemu/src/device/audio.c @@ -17,6 +17,8 @@ #include #include +#include + enum { reg_freq, reg_channels, @@ -30,13 +32,12 @@ enum { static uint8_t *sbuf = NULL; static uint32_t *audio_base = NULL; static uint32_t pos_read = 0; -static uint32_t audio_count = 0; +static atomic_char32_t audio_count = 0; #define MIN(a, b) ((a) < (b) ? (a) : (b)) static void audio_callback(void *userdata, uint8_t *stream, int len) { - SDL_LockAudio(); - uint32_t count = audio_count; + uint32_t count = atomic_load(&audio_count); uint32_t read_cnt = MIN(count, len); uint32_t to_end_cnt = CONFIG_SB_SIZE - pos_read; int32_t out_bound_cnt = read_cnt - to_end_cnt; @@ -50,8 +51,8 @@ static void audio_callback(void *userdata, uint8_t *stream, int len) { pos_read += read_cnt; pos_read %= CONFIG_SB_SIZE; // if (len > read_cnt) memset(stream + read_cnt, 0, len - read_cnt); - audio_count -= read_cnt; - SDL_UnlockAudio(); + count -= read_cnt; + atomic_store(&audio_count, count); } static inline void init_audio_dev() { @@ -85,11 +86,9 @@ static void audio_io_handler(uint32_t offset, int len, bool is_write) { } break; case reg_count: - SDL_LockAudio(); // TODO: must be add a lock here - if (is_write) audio_count = audio_base[reg_count]; - else audio_base[reg_count] = audio_count; - SDL_UnlockAudio(); + if (is_write) atomic_store(&audio_count, audio_base[reg_count]); + else audio_base[reg_count] = atomic_load(&audio_count); break; default: assert(0);