expand threaded example

This commit is contained in:
flysand7 2023-08-26 18:28:59 +11:00
parent 8b7850f03e
commit deb67217b5
1 changed files with 46 additions and 7 deletions

View File

@ -3,24 +3,63 @@
#include <stdlib.h>
#include <threads.h>
static void print_str(char *str) {
static void print_string_n(char *str, u64 len) {
fwrite(str, 1, len, stdout);
}
static void print_char(char c) {
print_string_n(&c, 1);
}
static void print_string(char *str) {
int str_len = 0;
while(str[str_len] != 0) {
++str_len;
str_len += 1;
}
fwrite(str, 1, str_len, stdout);
print_string_n(str, str_len);
}
static void print_int(i64 number) {
if(number < 0) {
print_char('-');
number = -number;
}
char buf[20];
buf[19] = 0;
char *p = buf + sizeof buf - 1;
do {
*--p = (number%10) + '0';
number /= 10;
} while(number > 0);
print_string(p);
}
volatile i64 counter = 0;
int thrd_func(void *arg) {
print_str("child thread: ok!\n");
print_string("child thread: ok!\n");
for(int i = 0; i < 100000; ++i) {
counter += 1;
}
print_string("child thread: counter = ");
print_int(counter);
print_char('\n');
for(;;);
return 0;
}
int main() {
print_str("main thread: before\n");
print_string("main thread: before\n");
thrd_t thrd;
thrd_create(&thrd, thrd_func, NULL);
print_str("main thread: after!\n");
int status = thrd_create(&thrd, thrd_func, NULL);
if(status == thrd_error) {
print_string("main thread: error creating child thread\n");
return 1;
}
print_string("main thread: after!\n");
for(int i = 0; i < 100000; ++i) {
counter += 1;
}
print_string("main thread: counter = ");
print_int(counter);
print_char('\n');
return 0;
}