Home | History | Annotate | Download | only in pthread_cond_timedwait
      1 /*
      2  * Copyright (c) 2002, Intel Corporation. All rights reserved.
      3  * Created by:  bing.wei.liu REMOVE-THIS AT intel DOT com
      4  * This file is licensed under the GPL license.  For the full content
      5  * of this license, see the COPYING file at the top level of this
      6  * source tree.
      7 
      8  * Test that pthread_cond_timedwait()
      9  *   shall return ETIMEDOUT if the time specified by 'abstime' has passed.
     10  *
     11  */
     12 
     13 #define _XOPEN_SOURCE 600
     14 
     15 #include <pthread.h>
     16 #include <stdio.h>
     17 #include <stdlib.h>
     18 #include <unistd.h>
     19 #include <sys/time.h>
     20 #include <errno.h>
     21 #include "posixtest.h"
     22 
     23 #define TIMEOUT   3
     24 
     25 struct testdata {
     26 	pthread_mutex_t mutex;
     27 	pthread_cond_t cond;
     28 } td;
     29 
     30 void *t1_func(void *arg)
     31 {
     32 	int rc;
     33 	struct timespec timeout;
     34 	struct timeval curtime;
     35 
     36 	(void) arg;
     37 
     38 	if (pthread_mutex_lock(&td.mutex) != 0) {
     39 		fprintf(stderr, "Thread1 failed to acquire the mutex\n");
     40 		exit(PTS_UNRESOLVED);
     41 	}
     42 	fprintf(stderr, "Thread1 started\n");
     43 
     44 	if (gettimeofday(&curtime, NULL) != 0) {
     45 		fprintf(stderr, "Fail to get current time\n");
     46 		exit(PTS_UNRESOLVED);
     47 	}
     48 	timeout.tv_sec = curtime.tv_sec + TIMEOUT;
     49 	timeout.tv_nsec = curtime.tv_usec * 1000;
     50 
     51 	fprintf(stderr, "Thread1 is waiting for the cond for %d seconds\n",
     52 		TIMEOUT);
     53 	rc = pthread_cond_timedwait(&td.cond, &td.mutex, &timeout);
     54 	if (rc == ETIMEDOUT) {
     55 		fprintf(stderr, "Thread1 stops waiting when time is out\n");
     56 		printf("Test PASSED\n");
     57 		exit(PTS_PASS);
     58 	} else {
     59 		fprintf(stderr,
     60 			"pthread_cond_timedwait return %d instead of ETIMEDOUT\n",
     61 			rc);
     62 		printf("Test FAILED\n");
     63 		exit(PTS_FAIL);
     64 	}
     65 }
     66 
     67 int main(void)
     68 {
     69 	pthread_t thread1;
     70 	void *th_ret;
     71 
     72 	if (pthread_mutex_init(&td.mutex, NULL) != 0) {
     73 		fprintf(stderr, "Fail to initialize mutex\n");
     74 		return PTS_UNRESOLVED;
     75 	}
     76 	if (pthread_cond_init(&td.cond, NULL) != 0) {
     77 		fprintf(stderr, "Fail to initialize cond\n");
     78 		return PTS_UNRESOLVED;
     79 	}
     80 
     81 	if (pthread_create(&thread1, NULL, t1_func, NULL) != 0) {
     82 		fprintf(stderr, "Fail to create thread 1\n");
     83 		return PTS_UNRESOLVED;
     84 	}
     85 
     86 	fprintf(stderr, "Main: no condition is going to be met\n");
     87 
     88 	pthread_join(thread1, &th_ret);
     89 	return (long)th_ret;
     90 }
     91