#include <sys/cdefs.h>
__RCSID("$NetBSD: t_condwait.c,v 1.10 2022/12/11 10:02:53 kre Exp $");
#include <sys/time.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <atf-c.h>
#include "isqemu.h"
#include "h_common.h"
#define WAITTIME 2
static const int debug = 1;
static void *
run(void *param)
{
struct timespec ts, to, te;
clockid_t clck;
pthread_condattr_t attr;
pthread_cond_t cond;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int ret = 0;
clck = *(clockid_t *)param;
PTHREAD_REQUIRE(pthread_condattr_init(&attr));
PTHREAD_REQUIRE(pthread_condattr_setclock(&attr, clck));
pthread_cond_init(&cond, &attr);
ATF_REQUIRE_EQ((ret = pthread_mutex_lock(&m)), 0);
ATF_REQUIRE_EQ(clock_gettime(clck, &ts), 0);
to = ts;
if (debug)
printf("started: %lld.%09ld sec\n", (long long)to.tv_sec,
to.tv_nsec);
ts.tv_sec += WAITTIME;
switch (ret = pthread_cond_timedwait(&cond, &m, &ts)) {
case ETIMEDOUT:
ATF_REQUIRE_EQ(clock_gettime(clck, &te), 0);
if (debug) {
printf("timeout: %lld.%09ld sec\n",
(long long)te.tv_sec, te.tv_nsec);
timespecsub(&te, &to, &to);
printf("elapsed: %lld.%09ld sec\n",
(long long)to.tv_sec, to.tv_nsec);
}
if (clck == CLOCK_MONOTONIC)
ATF_REQUIRE(timespeccmp(&te, &ts, >=));
break;
case 0:
atf_tc_fail("pthread_cond_timedwait returned before timeout");
break;
default:
ATF_REQUIRE_MSG(0, "pthread_cond_timedwait: %s", strerror(ret));
}
ATF_REQUIRE_MSG(!(ret = pthread_mutex_unlock(&m)),
"pthread_mutex_unlock: %s", strerror(ret));
pthread_exit(&ret);
}
static void
cond_wait(clockid_t clck, const char *msg) {
pthread_t child;
if (debug)
printf( "**** %s clock wait starting\n", msg);
ATF_REQUIRE_EQ(pthread_create(&child, NULL, run, &clck), 0);
ATF_REQUIRE_EQ(pthread_join(child, NULL), 0);
if (debug)
printf( "**** %s clock wait ended\n", msg);
}
ATF_TC(cond_wait_real);
ATF_TC_HEAD(cond_wait_real, tc)
{
atf_tc_set_md_var(tc, "descr", "Checks pthread_cond_timedwait "
"with CLOCK_REALTIME");
}
ATF_TC_BODY(cond_wait_real, tc) {
cond_wait(CLOCK_REALTIME, "CLOCK_REALTIME");
}
ATF_TC(cond_wait_mono);
ATF_TC_HEAD(cond_wait_mono, tc)
{
atf_tc_set_md_var(tc, "descr", "Checks pthread_cond_timedwait "
"with CLOCK_MONOTONIC");
}
ATF_TC_BODY(cond_wait_mono, tc) {
cond_wait(CLOCK_MONOTONIC, "CLOCK_MONOTONIC");
}
ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, cond_wait_real);
ATF_TP_ADD_TC(tp, cond_wait_mono);
return atf_no_error();
}