Path: blob/main/tools/regression/pthread/cv_cancel1/cv_cancel1.c
39536 views
/*-1* Copyright (c) 2006, David Xu <[email protected]>2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice unmodified, this list of conditions, and the following9* disclaimer.10* 2. Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR15* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES16* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.17* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,18* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT19* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,20* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY21* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF23* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24*25*/26#include <pthread.h>27#include <stdio.h>28#include <unistd.h>2930#define NLOOPS 103132static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;33static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;3435static int wake;36static int stop;3738static void *39thr_routine(void *arg __unused)40{41pthread_mutex_lock(&m);42while (wake == 0)43pthread_cond_wait(&cv, &m);44pthread_mutex_unlock(&m);4546while (stop == 0)47pthread_yield();48return (NULL);49}5051int52main(void)53{54pthread_t td;55int i;56void *result;5758pthread_setconcurrency(1);59for (i = 0; i < NLOOPS; ++i) {60stop = 0;61wake = 0;6263pthread_create(&td, NULL, thr_routine, NULL);64sleep(1);65printf("trying: %d\n", i);66pthread_mutex_lock(&m);67wake = 1;68pthread_cond_signal(&cv);69pthread_cancel(td);70pthread_mutex_unlock(&m);71stop = 1;72result = NULL;73pthread_join(td, &result);74if (result == PTHREAD_CANCELED) {75printf("the condition variable implementation does not\n"76"conform to SUSv3, a thread unblocked from\n"77"condition variable still can be canceled.\n");78return (1);79}80}8182printf("OK\n");83return (0);84}858687