Paste number 51031: thread create/join test

Paste number 51031: thread create/join test
Pasted by: keramida
When:1 year, 7 months ago
Share:Tweet this! | http://paste.lisp.org/+13DJ
Channel:None
Paste contents:
Raw Source | XML | Display As
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void dothread(long);
void *thread_main(void *);

long thread_count = 0;
pthread_mutex_t lock;

#define	LOCK() do {							\
	int errcode;							\
									\
	if ((errcode = pthread_mutex_lock(&lock)) != 0) {		\
		fprintf(stderr, "pthread_mutex_lock: "			\
		    "error %d: %s\n", errcode, strerror(errcode));	\
		exit(EXIT_FAILURE);					\
	}								\
} while (0)

#define	UNLOCK() do {							\
	int errcode;							\
									\
	if ((errcode = pthread_mutex_unlock(&lock)) != 0) {		\
		fprintf(stderr, "pthread_mutex_unlock: "		\
		    "error %d: %s\n", errcode, strerror(errcode));	\
		exit(EXIT_FAILURE);					\
	}								\
} while (0)

int
main(void)
{
	long count;
	int errcode;

	if ((errcode = pthread_mutex_init(&lock, NULL)) != 0) {
		fprintf(stderr, "pthread_mutex_init: "
		    "error %d: %s\n", errcode, strerror(errcode));
		exit(EXIT_FAILURE);
	}

	LOCK();
	thread_count = 0;
	UNLOCK();

	for (count = 0; count < 65536L; count++) {
		dothread(count);
	}

	LOCK();
	count = thread_count;
	UNLOCK();
	printf("%ld thread created and reaped.\n", count);
	fflush(stdout);
	exit(EXIT_SUCCESS);
}

void
dothread(long id)
{
	pthread_t td;
	int errcode;

	LOCK();
	thread_count = id;
	UNLOCK();

	if ((errcode = pthread_create(&td, NULL, thread_main, NULL)) != 0) {
		fprintf(stderr, "pthread_create: "
		    "error %d: %s\n", errcode, strerror(errcode));
		exit(EXIT_FAILURE);
	}

	if ((errcode = pthread_join(td, NULL)) != 0) {
		fprintf(stderr, "pthread_create: "
		    "error %d: %s\n", errcode, strerror(errcode));
		exit(EXIT_FAILURE);
	}
}

void *
thread_main(void *arg)
{
	long count;

	(void) arg;
	LOCK();
	count = thread_count;
	UNLOCK();

	printf("thread %ld running.\n", count);
	pthread_exit(NULL);
}

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.