00001 /* 00002 Thread example (mutex) 00003 AUP2, Sec. 5.17.3 00004 00005 Copyright 2003 by Marc J. Rochkind. All rights reserved. 00006 May be copied only for purposes and under conditions described 00007 on the Web page www.basepath.com/aup/copyright.htm. 00008 00009 The Example Files are provided "as is," without any warranty; 00010 without even the implied warranty of merchantability or fitness 00011 for a particular purpose. The author and his publisher are not 00012 responsible for any damages, direct or incidental, resulting 00013 from the use or non-use of these Example Files. 00014 00015 The Example Files may contain defects, and some contain deliberate 00016 coding mistakes that were included for educational reasons. 00017 You are responsible for determining if and how the Example Files 00018 are to be used. 00019 00020 */ 00021 #include "defs.h" 00022 #include <pthread.h> 00023 00024 /*[tx4]*/ 00025 static long get_and_incr_x(long incr) 00026 { 00027 static long x = 0; 00028 static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; 00029 long rtn; 00030 00031 ec_rv( pthread_mutex_lock(&mtx) ) 00032 rtn = x += incr; 00033 ec_rv( pthread_mutex_unlock(&mtx) ) 00034 return rtn; 00035 00036 EC_CLEANUP_BGN 00037 exit(EXIT_FAILURE); 00038 EC_CLEANUP_END 00039 } 00040 00041 static void *thread_func(void *arg) 00042 { 00043 while (get_and_incr_x(0) < (long)arg) { 00044 printf("Thread 2 says %ld\n", get_and_incr_x(1)); 00045 sleep(1); 00046 } 00047 return (void *)get_and_incr_x(0); 00048 } 00049 00050 int main(void) 00051 { 00052 pthread_t tid; 00053 void *status; 00054 00055 assert(sizeof(long) <= sizeof(void *)); 00056 ec_rv( pthread_create(&tid, NULL, thread_func, (void *)6) ) 00057 while (get_and_incr_x(0) < 10) { 00058 printf("Thread 1 says %ld\n", get_and_incr_x(1)); 00059 sleep(2); 00060 } 00061 ec_rv( pthread_join(tid, &status) ) 00062 printf("Thread 2's exit status is %ld\n", (long)status); 00063 return EXIT_SUCCESS; 00064 00065 EC_CLEANUP_BGN 00066 return EXIT_FAILURE; 00067 EC_CLEANUP_END 00068 } 00069 /*[]*/