Skip to content

Instantly share code, notes, and snippets.

@schn27

schn27/test.c Secret

Created August 23, 2021 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schn27/23b47563b429aaaad5ac315d05a43a11 to your computer and use it in GitHub Desktop.
Save schn27/23b47563b429aaaad5ac315d05a43a11 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <semaphore.h>
#include <stddef.h>
#include <stdio.h>
#include <time.h>
void *thread(void *arg) {
sem_t *sem = (sem_t *)arg;
for (size_t i = 0;; ++i) {
pthread_mutex_t mutexes[10];
for (size_t j = 0; j < sizeof(mutexes) / sizeof(mutexes[0]); ++j) {
pthread_mutex_init(&mutexes[j], NULL);
}
for (size_t j = 0; j < sizeof(mutexes) / sizeof(mutexes[0]); ++j) {
pthread_mutex_destroy(&mutexes[j]);
}
if ((i % 100) == 0) {
sem_post(sem);
}
}
return NULL;
}
#define THREADS 4
int main() {
pthread_t threads[THREADS];
sem_t sems[THREADS];
for (size_t i = 0; i < THREADS; ++i) {
sem_init(&sems[i], 0, 0);
pthread_create(&threads[i], NULL, thread, (void *)&sems[i]);
}
for (;;) {
for (size_t i = 0; i < THREADS; ++i) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1;
if (sem_timedwait(&sems[i], &ts) != 0) {
printf("\nthread #%d timeout\n", i);
return -1;
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment