Plan 9 from Bell Labs’s /usr/web/sources/contrib/axel/8021x/v100/timer.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <thread.h>
#include <bio.h>
#include <ip.h>
#include <mp.h>
#include <libsec.h>
#include <auth.h>
#include "dat.h"
#include "fns.h"

void
initTimers(Timers *s)
{
	if (s == nil)
		return;

	s->timer = nil;
	s->ntimer = 0;
	s->timerchan = chancreate(sizeof(int), 0);
}

Timer*
addTimer(Timers *s, char *name)
{
	Timer *t;

	if (s == nil)
		return nil;

	s->timer = realloc(s->timer, sizeof(Timer*)*(s->ntimer+1));
	if (s == nil)
		sysfatal("cannot reallocate Timers");

	t = malloc(sizeof(Timer));
	if (t == nil)
		sysfatal("cannot allocate Timer");

	syslog(0, logname, "addTimer %s", name);
	t->counter = 0;
	t->name = strdup(name);
	t->state = Off;
	s->timer[s->ntimer] = t;
	s->ntimer++;

	return t;
}

void
startTimer(Timer *t, int val)
{
	if (t == nil)
		return;

	syslog(0, logname, "startTimer %s to %d", t->name, val);
	if (t->state == Ticking)
		syslog(0, logname, "startTimer oops: %s runs, val=%d", t->name, t->counter/TickPerSec);
	t->state = Ticking;
	t->counter = val * TickPerSec;
}

void
resetTimer(Timer *t)
{
	if (t == nil)
		return;

	syslog(0, logname, "resetTimer %s (val was %d)", t->name, t->counter/TickPerSec);
	if (t->state == Off)
		syslog(0, logname, "startTimer oops: %s already off", t->name);
	t->state = Off;
	t->counter = 0;
}

void
clockproc(void *arg)
{
	Timers *s;
	Timer **t;
	Timer *expired;

	s = arg;

	for(;;) {
//		syslog(0, logname, "clockproc timer=%p ntimer=%d", s->timer, s->ntimer);
		expired = nil;
		for (t=&s->timer[0]; t < &s->timer[0] + s->ntimer; t++) {
			if ((*t)->state == Ticking && (*t)->counter == 0) {
				syslog(0, logname, "clockproc %s expired", (*t)->name);
				if (expired != nil)
					syslog(0, logname, "clockproc multiple timers expire: %s %s", (*t)->name, expired->name);
				(*t)->state = Expired;
				expired = *t;
			}
		}
		if (expired != nil) {
			syslog(0, logname, "clokproc sending on timerchan");
			send(s->timerchan, nil);
		}
		for (t=&s->timer[0]; t < &s->timer[0] + s->ntimer; t++) {
			if ((*t)->state == Ticking && (*t)->counter > 0)
				(*t)->counter--;
		}
		sleep(Tick);
	}
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.