userland: move more multithreading from cpp-cheat!

Convert infinite_loop.c into loop.c. Keep all examples fast by default!
This commit is contained in:
Ciro Santilli 六四事件 法轮功
2019-09-07 00:00:03 +00:00
parent 986d6cfb7b
commit e0fb39c92a
8 changed files with 165 additions and 14 deletions

50
userland/c/atomic.c Normal file
View File

@@ -0,0 +1,50 @@
/* https://cirosantilli.com/linux-kernel-module-cheat#c-multithreading */
#if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
#include <string.h>
#include <stdlib.h>
atomic_int acnt;
int cnt;
size_t niters;
int f(void *thr_data) {
(void)thr_data;
for (size_t i = 0; i < niters; ++i) {
++cnt;
++acnt;
}
return 0;
}
#endif
int main(int argc, char **argv) {
#if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
size_t nthreads;
thrd_t *threads;
if (argc > 1) {
nthreads = strtoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = strtoull(argv[2], NULL, 0);
} else {
niters = 10;
}
threads = malloc(sizeof(thrd_t) * nthreads);
for(size_t i = 0; i < nthreads; ++i)
thrd_create(threads + i, f, NULL);
for(size_t i = 0; i < nthreads; ++i)
thrd_join(threads[i], NULL);
free(threads);
printf("atomic %u\n", acnt);
printf("non-atomic %u\n", cnt);
#else
(void)argc;
(void)argv;
#endif
}

View File

@@ -3,7 +3,7 @@
* Loop and print an integer whenever a period is reached:
*
* ....
* ./infinite_loop [period=100000000 [max=0]]
* ./loop.out [max=10 [period=1]]
* ....
*
* * period: period for printing integers to stdout
@@ -19,27 +19,25 @@
int main(int argc, char **argv) {
uintmax_t i, j, period, max;
int max_given;
if (argc > 1) {
period = strtoumax(argv[1], NULL, 10);
max = strtoumax(argv[1], NULL, 10);
} else {
period = 100000000;
max = 10;
}
if (argc > 2) {
max = strtoumax(argv[2], NULL, 10);
max_given = 1;
period = strtoumax(argv[2], NULL, 10);
} else {
max_given = 0;
period = 1;
}
i = 0;
j = 0;
while (1) {
i++;
if (period != 0 && i % period == 0) {
printf("%ju\n", j);
j++;
}
if (max_given && i == max)
i++;
if (i == max)
break;
}
}