pthread_cond_destroy and cancel

Romano Paolo Tenca rotenca@telvia.it
Mon Jun 12 12:27:00 GMT 2006


This code creates a thread and use 2 cond var to sincronize.

Then the thread is cancelled and the thread hangs executing 
pthread_cond_destroy(&cv2).

The output is
  main: sleeping forever
  thread: try to destroy cv2

Where is the problem? In my code or in pthread_cond_destroy with a 
deferred cancel pending?

----------------------------start of code --------------------------
#include <windows.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>

/*
 * compiled with gcc version 3.2.3 (mingw special 20030504-1)
 * under XP Professional
 * linked with libpthreadGC2 2.7.0 prebuilt
 */
static pthread_cond_t cv1 =
    PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex1 =
    PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;
static pthread_cond_t cv2 =
    PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex2 =
    PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;

static void *func(void *arg){
    int err;
    // signal cv1
    pthread_mutex_lock(&mutex1);
    pthread_cond_signal(&cv1);
    pthread_mutex_lock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    // wait cv2
    pthread_cond_wait(&cv2, &mutex2);
    pthread_mutex_unlock(&mutex2);
    // to be sure that main calls cancel on this thread
    Sleep(50);
    //destroy mutex2 and cv2
    printf("thread: try to destroy cv2\n");
    err = pthread_cond_destroy(&cv2);
    printf("thread: cv2 err: %d\n",err); // bug? this is not executed
    pthread_mutex_destroy(&mutex2);
    return NULL;
}

void test(void){
    int err;
    pthread_t pid;
    pthread_mutex_lock(&mutex1);
    // create thread
    pthread_create(&pid, NULL, func, NULL);
    // wait cv1
    pthread_cond_wait(&cv1, &mutex1);
    pthread_mutex_lock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    // signal cv2
    pthread_cond_signal(&cv2);
    pthread_mutex_unlock(&mutex2);
    //cancel the thread
    err = pthread_cancel(pid);
    assert(err == 0);
    puts("main: sleeping forever");
    Sleep(INFINITE);
}

int main(int argc, char **argv) {
    test();
    return 0;
}

-- 
Romano Paolo Tenca



More information about the Pthreads-win32 mailing list