©2004 by Marc J. Rochkind. All rights reserved. Portions marked "Open Source" may be copied under license.

 

Main Page   Modules   Namespace List   Class Hierarchy   Compound List   File List   Namespace Members   Compound Members   File Members  

c5/tx3.c

Go to the documentation of this file.
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 /*[tx3]*/
00025 static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
00026 static long x = 0;
00027 
00028 static void *thread_func(void *arg)
00029 {
00030     bool done;
00031 
00032     while (true) {
00033         ec_rv( pthread_mutex_lock(&mtx) )
00034         done = x >= (long)arg;
00035         ec_rv( pthread_mutex_unlock(&mtx) )
00036         if (done)
00037             break;
00038         ec_rv( pthread_mutex_lock(&mtx) )
00039         printf("Thread 2 says %ld\n", ++x);
00040         ec_rv( pthread_mutex_unlock(&mtx) )
00041         sleep(1);
00042     }
00043     return (void *)x;
00044 
00045 EC_CLEANUP_BGN
00046     (void)pthread_mutex_unlock(&mtx);
00047     EC_FLUSH("thread_func")
00048     return NULL;
00049 EC_CLEANUP_END
00050 }
00051 
00052 int main(void)
00053 {
00054     pthread_t tid;
00055     void *status;
00056     bool done;
00057 
00058     assert(sizeof(long) <= sizeof(void *));
00059     ec_rv( pthread_create(&tid, NULL, thread_func, (void *)6) )
00060     while (true) {
00061         ec_rv( pthread_mutex_lock(&mtx) )
00062         done = x >= 10;
00063         ec_rv( pthread_mutex_unlock(&mtx) )
00064         if (done)
00065             break;
00066         ec_rv( pthread_mutex_lock(&mtx) )
00067         printf("Thread 1 says %ld\n", ++x);
00068         ec_rv( pthread_mutex_unlock(&mtx) )
00069         sleep(2);
00070     }
00071     ec_rv( pthread_join(tid, &status) )
00072     printf("Thread 2's exit status is %ld\n", (long)status);
00073     return EXIT_SUCCESS;
00074 
00075 EC_CLEANUP_BGN
00076     return EXIT_FAILURE;
00077 EC_CLEANUP_END
00078 }
00079 /*[]*/

Generated on Fri Apr 23 10:56:57 2004 for AUP2 Example Source by doxygen 1.3.1