/* * Condition variables demo: this demo simulates a semaphore using * mutex and condition variables * * Copyright (C) 2002 by Paolo Gai * Copyright (C) 2016 by Luca Abeni * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include #include struct mysem { pthread_mutex_t mutex; pthread_cond_t cond; int counter; }; static struct mysem mysem; void mysem_init(struct mysem *s, int num) { s->counter = num; pthread_mutex_init(&s->mutex, NULL); pthread_cond_init(&s->cond, NULL); } void mysem_wait(struct mysem *s) { pthread_mutex_lock(&s->mutex); while (!s->counter) { pthread_cond_wait(&s->cond, &s->mutex); } s->counter--; pthread_mutex_unlock(&s->mutex); } void mysem_post(struct mysem *s) { pthread_mutex_lock(&s->mutex); s->counter++; pthread_cond_signal(&s->cond); pthread_mutex_unlock(&s->mutex); } /** * Here is the real program... */ void *body(void *arg) { int j; mysem_wait(&mysem); for (j=0; j<40; j++) { usleep(200000); fprintf(stderr, "%s", (char *)arg); } mysem_post(&mysem); return NULL; } int main(int argc, char *argv[]) { pthread_t t1,t2,t3; mysem_init(&mysem,1); pthread_create(&t1, NULL, body, (void *)"."); pthread_create(&t2, NULL, body, (void *)"#"); pthread_create(&t3, NULL, body, (void *)"o"); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); printf("\n"); return 0; }