/* mtdemo.c by Pieter Suurmond, februari 1, 2003. Copyleft. Thanks to Marc Groenewegen, Dinkum Technology, The Netherlands. */ #include #include #include /* For sleep() */ #include /* POSIX threads. */ void* engine_A(void* num) { int t, n = *((int*)num); /* Read from shared mem. */ char space[8]; /* Is printf() atomic? */ for (t = 0; t < n; t++) space[t] = '\t'; space[t] = '\0'; for (t = 0; t < 20; t += n) /* For 20 seconds. */ { printf("%sengine_A %d: %d\n", space, n, t); sleep(n); } return (void*)NULL; } void* engine_B(void* num) /* Two instances are run. */ { int t, n = *((int*)num); char space[8]; for (t = 0; t < n; t++) space[t] = '\t'; space[t] = '\0'; for (t = 0; t < 20; t += n) /* Also for 20 seconds. */ { printf("%sengine_B %d: %d\n", space, n, t); sleep(n); } return (void*)NULL; } int main() { pthread_t t1, t2, t3; void* retval; int a = 1, b = 2, /* Create 3 threads, one of */ c = 3; /* type A and two of type B. */ printf("Program mtdemo started.\n"); if (pthread_create(&t1, NULL, engine_A, (void*)&a) || pthread_create(&t2, NULL, engine_B, (void*)&b) || pthread_create(&t3, NULL, engine_B, (void*)&c)) { printf("pthread_create() failed!\n"); exit(1); } printf("Parent created 3 children.\n"); if (pthread_join(t1, &retval) || /* Collapse threads. */ pthread_join(t2, &retval) || pthread_join(t3, &retval)) { printf("pthread_join() failed!\n"); exit(1); } printf("Parent joined threads, done.\n"); exit(0); }