1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <stdio.h> #include <stdlib.h> #include <pthread.h>
pthread_mutex_t mutex; int order = 0;
typedef struct __run_attr { char charToPrint; int order; } run_attr_t;
void *thread_run(void *arg) { run_attr_t *run = (run_attr_t *)arg; int runCount = 0; while (1) { pthread_mutex_lock(&mutex); if (order % 3 == run->order) { printf("%#lx %c\n", pthread_self(), run->charToPrint); order++; runCount++; } pthread_mutex_unlock(&mutex);
if (runCount == 10) { break; } }
return NULL; }
int main(int argc, char * argv[]) { pthread_t pidA, pidB, pidC; pthread_mutex_init(&mutex, 0); run_attr_t Aattr = {'A', 0}; run_attr_t Battr = {'B', 1}; run_attr_t Cattr = {'C', 2}; pthread_create(&pidA, NULL, thread_run, &Aattr); pthread_create(&pidB, NULL, thread_run, &Battr); pthread_create(&pidC, NULL, thread_run, &Cattr); pthread_join(pidA, NULL); pthread_join(pidB, NULL); pthread_join(pidC, NULL); pthread_mutex_destroy(&mutex); return 0; }
|