Hello there. Can you provide me with an implementation of a conditional variable in C…
- User
Hello there. Can you provide me with an implementation of a conditional variable in C using semaphores and mutexes?
- Assistant
#include <pthread.h> #include <semaphore.h>
typedef struct { sem_t sem; pthread_mutex_t mutex; int flag; } cond_var_t;
void cond_var_init(cond_var_t* cv) { sem_init(&cv->sem, 0, 0); pthread_mutex_init(&cv->mutex, NULL); cv->flag = 0; }
void cond_var_signal(cond_var_t* cv) { pthread_mutex_lock(&cv->mutex); cv->flag = 1; sem_post(&cv->sem); pthread_mutex_unlock(&cv->mutex); }
void cond_var_wait(cond_var_t* cv) { pthread_mutex_lock(&cv->mutex); while (cv->flag == 0) { pthread_mutex_unlock(&cv->mutex); sem_wait(&cv->sem); pthread_mutex_lock(&cv->mutex); } cv->flag = 0; pthread_mutex_unlock(&cv->mutex); }
void cond_var_destroy(cond_var_t* cv) { sem_destroy(&cv->sem); pthread_mutex_destroy(&cv->mutex); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →