/* * Mutex demo * * Copyright (C) 2002 Paolo Gai * Copyright (C) 2007 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 #define __USE_UNIX98 #include static pthread_mutex_t mymutex, mymutex1; static int th_cnt; static void *body(void *arg) { int j; pthread_mutex_lock(&mymutex1); fprintf(stderr, "Thread %d: %s\n", th_cnt++, (char *)arg); pthread_mutex_unlock(&mymutex1); pthread_mutex_lock(&mymutex); for (j=0; j<20; j++) { usleep(500000); fprintf(stderr, "%s", (char *)arg); } pthread_mutex_unlock(&mymutex); return NULL; } int main(int argc, char *argv[]) { pthread_t t1, t2, t3; int err; pthread_attr_t attrs; struct sched_param sp; int pmin; pthread_mutexattr_t mymutexattr; pthread_mutexattr_init(&mymutexattr); pthread_mutexattr_setprotocol(&mymutexattr, PTHREAD_PRIO_INHERIT); pthread_mutex_init(&mymutex, &mymutexattr); pthread_mutex_init(&mymutex1, &mymutexattr); pthread_mutexattr_destroy(&mymutexattr); pthread_attr_init(&attrs); pthread_attr_setinheritsched(&attrs, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&attrs, SCHED_FIFO); pmin = sched_get_priority_min(SCHED_FIFO); sp.sched_priority = pmin + 1; err = pthread_attr_setschedparam(&attrs, &sp); err = pthread_create(&t1, &attrs, body, "."); if (err) { fprintf(stderr, "Error creating thread!\n"); return -1; } sp.sched_priority = pmin + 2; err = pthread_attr_setschedparam(&attrs, &sp); err = pthread_create(&t2, &attrs, body, "#"); if (err) { fprintf(stderr, "Error creating thread!\n"); return -1; } sp.sched_priority = pmin + 3; err = pthread_attr_setschedparam(&attrs, &sp); err = pthread_create(&t3, &attrs, body, "o"); if (err) { fprintf(stderr, "Error creating thread!\n"); return -1; } pthread_attr_destroy(&attrs); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); printf("\n"); return 0; }