|
@@ -0,0 +1,103 @@
|
|
|
+
|
|
|
+ *
|
|
|
+ * Test case that illustrates a timed wait on a condition variable.
|
|
|
+ */
|
|
|
+
|
|
|
+#include <errno.h>
|
|
|
+#include <stdio.h>
|
|
|
+#include <string.h>
|
|
|
+#include <pthread.h>
|
|
|
+#include <sys/time.h>
|
|
|
+#include <unistd.h>
|
|
|
+
|
|
|
+
|
|
|
+typedef struct {
|
|
|
+ pthread_mutex_t mutex;
|
|
|
+ pthread_cond_t cond;
|
|
|
+ int flag;
|
|
|
+} event_t;
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+event_t main_event;
|
|
|
+
|
|
|
+
|
|
|
+void *
|
|
|
+test_thread (void *ms_param)
|
|
|
+{
|
|
|
+ int status = 0;
|
|
|
+ event_t foo;
|
|
|
+ struct timespec time;
|
|
|
+ struct timeval now;
|
|
|
+ long ms = (long) ms_param;
|
|
|
+
|
|
|
+
|
|
|
+ pthread_cond_init(&foo.cond, NULL);
|
|
|
+ pthread_mutex_init(&foo.mutex, NULL);
|
|
|
+ foo.flag = 0;
|
|
|
+
|
|
|
+
|
|
|
+ printf("waiting %ld ms ...\n", ms);
|
|
|
+ gettimeofday(&now, NULL);
|
|
|
+ time.tv_sec = now.tv_sec + ms/1000 + (now.tv_usec + (ms%1000)*1000)/1000000;
|
|
|
+ time.tv_nsec = ((now.tv_usec + (ms%1000)*1000) % 1000000) * 1000;
|
|
|
+
|
|
|
+
|
|
|
+ pthread_mutex_lock(&foo.mutex);
|
|
|
+ while (foo.flag == 0 && status != ETIMEDOUT) {
|
|
|
+ status = pthread_cond_timedwait(&foo.cond, &foo.mutex, &time);
|
|
|
+ }
|
|
|
+ pthread_mutex_unlock(&foo.mutex);
|
|
|
+
|
|
|
+
|
|
|
+ pthread_mutex_lock(&main_event.mutex);
|
|
|
+ main_event.flag = 1;
|
|
|
+ pthread_cond_signal(&main_event.cond);
|
|
|
+ pthread_mutex_unlock(&main_event.mutex);
|
|
|
+
|
|
|
+
|
|
|
+ return (void*) status;
|
|
|
+}
|
|
|
+
|
|
|
+int
|
|
|
+main (void)
|
|
|
+{
|
|
|
+ unsigned long count;
|
|
|
+
|
|
|
+ setvbuf (stdout, NULL, _IONBF, 0);
|
|
|
+
|
|
|
+
|
|
|
+ pthread_cond_init(&main_event.cond, NULL);
|
|
|
+ pthread_mutex_init(&main_event.mutex, NULL);
|
|
|
+ main_event.flag = 0;
|
|
|
+
|
|
|
+ for (count = 0; count < 20; ++count)
|
|
|
+ {
|
|
|
+ pthread_t thread;
|
|
|
+ int status;
|
|
|
+
|
|
|
+
|
|
|
+ status = pthread_create (&thread, NULL, test_thread, (void*) (count*100));
|
|
|
+ if (status != 0) {
|
|
|
+ printf ("status = %d, count = %lu: %s\n", status, count,
|
|
|
+ strerror (errno));
|
|
|
+ return 1;
|
|
|
+ }
|
|
|
+ else {
|
|
|
+
|
|
|
+
|
|
|
+ pthread_mutex_lock(&main_event.mutex);
|
|
|
+ while (main_event.flag == 0) {
|
|
|
+ pthread_cond_wait(&main_event.cond, &main_event.mutex);
|
|
|
+ }
|
|
|
+ main_event.flag = 0;
|
|
|
+ pthread_mutex_unlock(&main_event.mutex);
|
|
|
+
|
|
|
+ printf ("count = %lu\n", count);
|
|
|
+ }
|
|
|
+
|
|
|
+ usleep (10);
|
|
|
+ }
|
|
|
+
|
|
|
+ return 0;
|
|
|
+}
|