#include #include #include #include #include #include pthread_mutex_t mtx; pthread_cond_t cv; void mutex_lock() { if (pthread_mutex_lock(&mtx) != 0) _exit(3); } void mutex_unlock() { if (pthread_mutex_unlock(&mtx) != 0) _exit(3); } int main() { if (0 != pthread_mutex_init(&mtx,0)) return 1; if (0 != pthread_cond_init(&cv,0)) return 2; while(1) { int i; for (i=0; i<3; ++i) { mutex_lock(); const time_t wait_time = time(0)+1; struct timespec tm; tm.tv_sec = wait_time; tm.tv_nsec = 0; const int err = pthread_cond_timedwait(&cv, &mtx, &tm); if (err != ETIMEDOUT) { printf("error cond\n"); return 4; } const time_t end_time = time(0); mutex_unlock(); if (end_time < wait_time) { printf("wait:%lu wakeup:%lu\n", (long)wait_time, (long)end_time); assert(!"early wakeup"); } printf("OK\n"); } const long s = random() % 100000; printf("switch, sleep %l ms\n", s); usleep(s); } }