git » libfilo » master » tree

[master] / tests / lockloco.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sched.h>

#include "libfilo.h"


#define MAXSTART	100
#define MAXLEN		200
#define MAXDELAY	100000

filock_t l;

void *locoth(void *unused) {
	int mode;
	long delay;
	off_t start, len;
	struct timespec ts;
	unsigned int count = 0;

	for (;;) {
		start = rand() % MAXSTART;
		len = rand() % MAXLEN;
		delay = rand() % MAXDELAY;

		/* 2 readers, 1 writer */
		mode = rand() % 3;
		mode = mode ? FL_RD_MODE : FL_WR_MODE;

		ts.tv_sec = 0;
		ts.tv_nsec = delay;
#if 1
		//printf("%lu\tl %d\t %lu\t %lu\n", pthread_self(), mode, start, len);
		filo_lock(&l, start, len, mode);
#else
		if (filo_trylock(&l, start, len, mode) == 0) {
			printf("%lu\tC %d\t %lu\t %lu\n", pthread_self(), mode, start, len);
			filo_lock(&l, start, len, mode);
			printf("%lu\tA %d\t %lu\t %lu\n", pthread_self(), mode, start, len);

		} else {
			printf("%lu\tl %d\t %lu\t %lu\n", pthread_self(), mode, start, len);
		}
#endif
		/* sleep in 1 out of 20 */
		/*
		if ((start + len) % 20 == 0) {
			nanosleep(&ts, NULL);
		} else {
			sched_yield();
		}
		*/
		sched_yield();
		//printf("%lu\tu %d\t %lu\t %lu\n", pthread_self(), mode, start, len);
		filo_unlock(&l, start, len);

		count++;
		if (count % 50000 == 0) {
			printf("%lu\t %d\n", pthread_self(), count);
			//printf("\t %d\t %lu\t %lu\n", mode, start, len);
			//fflush(stdout);
		}
	}
	return NULL;
}

int main(void) {
	pthread_t t1, t2, t3;

	filo_init(&l);

	srand(time(NULL));

	pthread_create(&t1, NULL, &locoth, NULL);
	pthread_create(&t2, NULL, &locoth, NULL);
	pthread_create(&t3, NULL, &locoth, NULL);

	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	pthread_join(t3, NULL);
	return 0;

}