Newer
Older
src / c / c-tutorial / thread2.c
  1. #include <pthread.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5.  
  6.  
  7. int myglobal;
  8.  
  9. void *thread_function ( void *arg ) {
  10. int i,j;
  11. for ( i = 0; i < 20; i++ ) {
  12. j = myglobal;
  13. j = j + 1;
  14. printf(".");
  15. fflush(stdout);
  16. sleep(2);
  17. myglobal = j;
  18. }
  19.  
  20. return NULL;
  21. }
  22.  
  23. int main ( void ) {
  24.  
  25. pthread_t mythread;
  26. int i;
  27.  
  28. if ( pthread_create(&mythread, NULL, thread_function, NULL) ) {
  29. printf("error creating thread.\n");
  30. abort();
  31. }
  32.  
  33. for ( i = 0; i < 20; i++) {
  34. myglobal = myglobal + 1;
  35. printf("o");
  36. fflush(stdout);
  37. sleep(1);
  38. }
  39.  
  40. if ( pthread_join(mythread, NULL) ) {
  41. printf("error joining thread");
  42. abort();
  43. }
  44.  
  45. printf("\nmyglobal equals %d", myglobal);
  46.  
  47. exit(0);
  48. }