/* Lecture_2/simple_sem.c * James S. Plank Continuation-Based Thread Library - A non-preemptive, continuation-based thread library. Copyright (C) 2009 James S. Plank This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Original: October, 1995 Revised: January, 2009 James S. Plank Department of Electrical Engineering and Computer Science University of Tennessee Knoxville, TN 37996 plank@cs.utk.edu */ #include #include #include "cbthread.h" typedef struct { cbthread_gsem semaphore; int counter; } Tinfo; void consumer(Tinfo *t); void producer(Tinfo *t) { t->counter++; printf("%8.3lf Producer %d\n", cbthread_get_fake_time(), t->counter); cbthread_gsem_V(t->semaphore); cbthread_fake_sleep(drand48(), producer, t); } void consumer_unblocked(Tinfo *t) { printf("%8.3lf Consumer %d finished\n", cbthread_get_fake_time(), t->counter); cbthread_fake_sleep(drand48(), consumer, t); } void consumer(Tinfo *t) { t->counter++; printf("%8.3lf Consumer %d starting\n", cbthread_get_fake_time(), t->counter); cbthread_gsem_P(t->semaphore, consumer_unblocked, t); } main() { int i; Tinfo *p, *c; cbthread_gsem s; srand48(time(0)); s = cbthread_make_gsem(0); p = (Tinfo *) malloc(sizeof(Tinfo)); p->semaphore = s; p->counter = 0; cbthread_fork(producer, p); c = (Tinfo *) malloc(sizeof(Tinfo)); c->semaphore = s; c->counter = 0; cbthread_fork(consumer, c); cbthread_fake_sleep(3.00, exit, NULL); }