ex1.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /* Creates two threads, one printing 10000 "a"s, the other printing
  2. 10000 "b"s.
  3. Illustrates: thread creation, thread joining. */
  4. #include <stddef.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include "pthread.h"
  8. void * process(void * arg)
  9. {
  10. int i;
  11. fprintf(stderr, "Starting process %s\n", (char *) arg);
  12. for (i = 0; i < 10000; i++) {
  13. write(1, (char *) arg, 1);
  14. }
  15. return NULL;
  16. }
  17. int main(void)
  18. {
  19. int retcode;
  20. pthread_t th_a, th_b;
  21. void * retval;
  22. retcode = pthread_create(&th_a, NULL, process, (void *) "a");
  23. if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);
  24. else fprintf(stderr, "create a succeeded %d\n", retcode);
  25. retcode = pthread_create(&th_b, NULL, process, (void *) "b");
  26. if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);
  27. else fprintf(stderr, "create b succeeded %d\n", retcode);
  28. retcode = pthread_join(th_a, &retval);
  29. if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);
  30. else fprintf(stderr, "join a succeeded %d\n", retcode);
  31. retcode = pthread_join(th_b, &retval);
  32. if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);
  33. else fprintf(stderr, "join b succeeded %d\n", retcode);
  34. return 0;
  35. }