خرید بک لینک

Vote count: 0

Is there a way to make it so I can have threads run a certain function when other threads are not locking other functions?

I want to achieve something like:

pthread_t threadID[10];
pthread_mutex_t blocking;
pthread_mutex_init(&blocking, NULL);
pthread_cond_t go;
pthread_cond_init(&go, NULL);

void * function1() {
    pthread_mutex_lock(&blocking); // Only one thread at a time!
    // Do some work
    pthread_cond_broadcast(&go);
    pthread_mutex_unlock(&blocking);
}

void * function2() {
    pthread_cond_wait(&go, NULL); // Imagine 5 threads waiting here.
    // Does some work too!
}

What I want is basically that threads run function2, when no threads are ruing in function1.

I do not wish to lock function2 as threads may execute it concurrently without a problem, so I know the pthread_cond_wait(&go, NULL) will not work (even the NULL argument is a bit silly). Also, a broadcast will signal all waiting threads, but only one of those threads will make it to the critical code section. I'm aiming to unlock all threads with a signal, and allow all those threads to execute the code.

I know there are ways to do this without going into thread locking mechanisms (like having a variable be modified inside function1 and function2 must check its value before allowing threads to move forward), but I was wondering if there is a way with mutexes and condition variables, not semaphores.

asked 52 secs ago

برچسب: نویسنده: استخدام کار تاريخ: يکشنبه 12 ارديبهشت 1395 ساعت: 7:11

صفحه بندی