Add write lock to printf

This commit is contained in:
flysand7 2023-09-12 04:40:29 +11:00
parent 4917b05771
commit 5453813e39
4 changed files with 18 additions and 11 deletions

1
cia.c
View File

@ -30,6 +30,7 @@
#include "src/stdlib-thread/thread.c"
// Module stdlib_file
#include "src/stdlib-file/common.c"
#include "src/stdlib-file/file.c"
#include "src/stdlib-file/fmt.c"

8
src/stdlib-file/common.c Normal file
View File

@ -0,0 +1,8 @@
FILE *stdin;
FILE *stdout;
FILE *stderr;
static Cia_Pool _page_allocator;
static Cia_Pool _file_pool;
static Cia_Mutex _g_pool_mutex;

View File

@ -1,12 +1,4 @@
FILE *stdin;
FILE *stdout;
FILE *stderr;
static Cia_Pool _page_allocator;
static Cia_Pool _file_pool;
static Cia_Mutex _g_pool_mutex;
static void _fileapi_init() {
cia_pool_create(&_file_pool, cia_allocator_pages(), 0x1000, sizeof(FILE), 16);
stdin = cia_pool_alloc(&_file_pool);

View File

@ -82,6 +82,7 @@ int printf(const char *restrict fmt, ...) {
i64 buf_start_idx = 0;
i64 buf_end_idx = 0;
u64 unused;
cia_mutex_lock(&stdout->mutex);
for(i64 i = 0; fmt[i] != 0;) {
buf_start_idx = i;
buf_end_idx = i;
@ -98,7 +99,7 @@ int printf(const char *restrict fmt, ...) {
, &unused
);
if(status != _RT_STATUS_OK) {
return -1;
goto _error;
}
ret_printed += buf_size;
}
@ -129,16 +130,21 @@ int printf(const char *restrict fmt, ...) {
int ch = va_arg(args, int);
_RT_Status status = _rt_file_write(&stdout->rt_file, 1, &ch, &unused);
if(status != _RT_STATUS_OK) {
return -1;
goto _error;
}
arg_chars = 1;
}
i += 1;
if(arg_chars < 0) {
return -1;
goto _error;
}
ret_printed += arg_chars;
}
cia_mutex_unlock(&stdout->mutex);
va_end(args);
return ret_printed;
_error:
cia_mutex_unlock(&stdout->mutex);
va_end(args);
return -1;
}