Skip to content

Commit 5453813

Browse files
committed
Add write lock to printf
1 parent 4917b05 commit 5453813

File tree

4 files changed

+18
-11
lines changed

4 files changed

+18
-11
lines changed

cia.c

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
#include "src/stdlib-thread/thread.c"
3131

3232
// Module stdlib_file
33+
#include "src/stdlib-file/common.c"
3334
#include "src/stdlib-file/file.c"
3435
#include "src/stdlib-file/fmt.c"
3536

src/stdlib-file/common.c

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
FILE *stdin;
3+
FILE *stdout;
4+
FILE *stderr;
5+
6+
static Cia_Pool _page_allocator;
7+
static Cia_Pool _file_pool;
8+
static Cia_Mutex _g_pool_mutex;

src/stdlib-file/file.c

-8
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,4 @@
11

2-
FILE *stdin;
3-
FILE *stdout;
4-
FILE *stderr;
5-
6-
static Cia_Pool _page_allocator;
7-
static Cia_Pool _file_pool;
8-
static Cia_Mutex _g_pool_mutex;
9-
102
static void _fileapi_init() {
113
cia_pool_create(&_file_pool, cia_allocator_pages(), 0x1000, sizeof(FILE), 16);
124
stdin = cia_pool_alloc(&_file_pool);

src/stdlib-file/fmt.c

+9-3
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ int printf(const char *restrict fmt, ...) {
8282
i64 buf_start_idx = 0;
8383
i64 buf_end_idx = 0;
8484
u64 unused;
85+
cia_mutex_lock(&stdout->mutex);
8586
for(i64 i = 0; fmt[i] != 0;) {
8687
buf_start_idx = i;
8788
buf_end_idx = i;
@@ -98,7 +99,7 @@ int printf(const char *restrict fmt, ...) {
9899
, &unused
99100
);
100101
if(status != _RT_STATUS_OK) {
101-
return -1;
102+
goto _error;
102103
}
103104
ret_printed += buf_size;
104105
}
@@ -129,16 +130,21 @@ int printf(const char *restrict fmt, ...) {
129130
int ch = va_arg(args, int);
130131
_RT_Status status = _rt_file_write(&stdout->rt_file, 1, &ch, &unused);
131132
if(status != _RT_STATUS_OK) {
132-
return -1;
133+
goto _error;
133134
}
134135
arg_chars = 1;
135136
}
136137
i += 1;
137138
if(arg_chars < 0) {
138-
return -1;
139+
goto _error;
139140
}
140141
ret_printed += arg_chars;
141142
}
143+
cia_mutex_unlock(&stdout->mutex);
142144
va_end(args);
143145
return ret_printed;
146+
_error:
147+
cia_mutex_unlock(&stdout->mutex);
148+
va_end(args);
149+
return -1;
144150
}

0 commit comments

Comments
 (0)