💾 Archived View for thrig.me › blog › 2023 › 09 › 28 › stuckbusy.c captured on 2024-08-18 at 20:41:20.

View Raw

More Information

⬅️ Previous capture (2023-09-28)

-=-=-=-=-=-=-

#include <err.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

volatile int foo;

void *
busybee(void *unused)
{
	while (1) {
		nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 99999},
		          NULL);
		foo++;
	}
}

int
main(void)
{
	char buf[1];
	int fds[2];
	pthread_t th1, th2, th3, th4;
	if (pipe(fds) != 0) err(1, "pipe");
	if (pthread_create(&th1, NULL, busybee, NULL) != 0)
		err(1, "pthread_create");
	if (pthread_create(&th2, NULL, busybee, NULL) != 0)
		err(1, "pthread_create");
	if (pthread_create(&th3, NULL, busybee, NULL) != 0)
		err(1, "pthread_create");
	if (pthread_create(&th4, NULL, busybee, NULL) != 0)
		err(1, "pthread_create");
	while (1) {
		read(fds[0], buf, 1);
		fprintf(stderr, "not stuck\n");
	}
}