/* * $RCSfile: index.html,v $ * * Simple POSIX threads example * uses a mutex so two threads can change * a global variable without creating a * race condition * * rcampos@dcmonster.com * $Id: index.html,v 1.6 2005/05/18 00:02:55 rcampos Exp rcampos $ * */ #include #include #include #include void threadFunc(int); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int globalvar = 0; static char rcsid[] = "$Id: index.html,v 1.6 2005/05/18 00:02:55 rcampos Exp rcampos $"; int main(int argc, char *argv[]) { pthread_t t1, t2; int argt1, argt2; int rc[2]; if (argc < 3) { fprintf(stderr, "Usage:\n\t%s g \n\tWhere arg1 and arg2 are integer\n", argv[0]); exit(1); } argt1 = atoi(argv[1]); argt2 = atoi(argv[2]); /* int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); */ /* Create first thread, rc will hold the return code for pthread_create */ rc[0] = pthread_create(&t1, NULL, (void *)threadFunc, (void *) argt1); rc[1] = pthread_create(&t2, NULL, (void *)threadFunc, (void *) argt2); /* pthread_create should return 0, otherwise something is wrong */ if (rc[0] != 0 || rc[1] != 0) { perror("main: error creating threads"); exit(1); } /* Wait for the first thread to finish */ rc[0] = pthread_join(t1, NULL); rc[1] = pthread_join(t2, NULL); if (rc[0] != 0 || rc[1] != 0) { perror("main: error joining threads"); exit(1); } else { printf("main: threads returned successfully\n"); } printf("main: argt1 = %d, argt2 = %d\n", argt1, argt2); printf("main: globalvar is %d\n", globalvar); return 0; } void threadFunc(int arg) { pthread_t myId; myId = pthread_self(); printf("threadFunc: my ID is %d\n", myId); printf("threadFunc: my arg is %d\n", arg); pthread_mutex_lock(&mutex); globalvar += arg; pthread_mutex_unlock(&mutex); printf("threadFunc: globalvar is %d\n", globalvar); } O resultado na prática, após a compilação, é o seguinte: rcampos ~ $ gcc -o simple_mutex_var simple_mutex_var.c rcampos ~ $ ./simple_mutex_var 30 -10 threadFunc: my ID is 41944064 threadFunc: my arg is 30 threadFunc: globalvar is 30 threadFunc: my ID is 41945088 threadFunc: my arg is -10 threadFunc: globalvar is 20 main: threads returned successfully main: argt1 = 30, argt2 = -10 main: globalvar is 20