pthread.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * pthread.c:
  3. * Tiny test program to see whether POSIX threads work.
  4. */
  5. static const char rcsid[] = "$Id: pthread.c,v 1.4 2005/10/26 22:56:05 chris Exp $";
  6. #include <sys/types.h>
  7. #include <errno.h>
  8. #include <pthread.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include <unistd.h>
  13. static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  14. static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  15. static int return_value = -1;
  16. void *worker_thread(void *v) {
  17. /* Record successful return and signal parent to wake up. */
  18. return_value = 0;
  19. pthread_mutex_lock(&mtx);
  20. pthread_cond_signal(&cond);
  21. pthread_mutex_unlock(&mtx);
  22. while (1) {
  23. sleep(1);
  24. pthread_testcancel();
  25. }
  26. }
  27. /* Start a thread, and have it set a variable to some other value, then signal
  28. * a condition variable. If this doesn't happen within some set time, we assume
  29. * that something's gone badly wrong and abort (for instance, the thread never
  30. * got started). */
  31. int main(void) {
  32. pthread_t thr;
  33. int res;
  34. struct timespec deadline = {0};
  35. if ((res = pthread_mutex_lock(&mtx)) != 0
  36. || (res = pthread_create(&thr, NULL, worker_thread, NULL)) != 0) {
  37. fprintf(stderr, "%s\n", strerror(res));
  38. return -1;
  39. }
  40. /* Thread should now be running; we should wait on the condition
  41. * variable. */
  42. do
  43. deadline.tv_sec = 2 + time(NULL);
  44. while ((res = pthread_cond_timedwait(&cond, &mtx, &deadline)) == EINTR);
  45. if (res != 0) {
  46. fprintf(stderr, "%s\n", strerror(res));
  47. return -1;
  48. }
  49. if ((res = pthread_cancel(thr)) != 0
  50. || (res = pthread_join(thr, NULL)) != 0) {
  51. fprintf(stderr, "%s\n", strerror(res));
  52. return -1;
  53. }
  54. return return_value;
  55. }