Files
linux-kernel-module-cheat/userland/posix/pthread_mutex.c
Ciro Santilli 六四事件 法轮功 ce3ea9faea Comment on gem5's broken GDB on secondary core
Try to assert on all C programs if thread creation failed. C++ already
throws by default.
2020-06-11 01:00:00 +00:00

52 lines
1.3 KiB
C

/* https://cirosantilli.com/linux-kernel-module-cheat#pthread-mutex */
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
unsigned long long global = 0;
pthread_mutex_t main_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
void* main_thread(void *arg) {
unsigned long long niters = *(unsigned long long *)arg;
unsigned long long i;
for (i = 0; i < niters; ++i) {
pthread_mutex_lock(&main_thread_mutex);
global++;
pthread_mutex_unlock(&main_thread_mutex);
}
return NULL;
}
int main(int argc, char **argv) {
pthread_t *threads;
unsigned long long i, niters, nthreads;
/* CLI arguments. */
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(pthread_t) * nthreads);
/* Action */
for (i = 0; i < nthreads; ++i)
assert(!pthread_create(&threads[i], NULL, main_thread, &niters));
for (i = 0; i < nthreads; ++i)
assert(!pthread_join(threads[i], NULL));
assert(global == nthreads * niters);
/* Cleanup. */
free(threads);
return EXIT_SUCCESS;
}