Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdbool.h>
- #include <pthread.h>
- #include <stdlib.h>
- /*
- 条件变量的用途
- 按现在的我理解(不一定对),我们可以把条件变量当成一种「信号」(不是那个「信号量」)来使用。
- 对于一个「信号」,我们就有两种操作「等待」和「通知」(暂时忽略实现细节)
- */
- struct _Condition;
- typedef struct _Condition Condition;
- Condition *
- ConditionNew();
- void
- ConditionWait(Condition *condition);
- void
- ConditionNotify(Condition *condition);
- struct _Condition {
- bool signaled;
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- };
- Condition *
- ConditionNew() {
- Condition *c = malloc(sizeof(Condition));
- c->signaled = false;
- pthread_mutex_init(&c->mutex, NULL);
- pthread_cond_init(&c->cond, NULL);
- return c;
- }
- void
- ConditionWait(Condition *condition) {
- Condition *c = condition;
- pthread_mutex_lock(&c->mutex);
- while (!c->signaled) {
- pthread_cond_wait(&c->cond, &c->mutex);
- }
- c->signaled = false;
- pthread_mutex_unlock(&c->mutex);
- }
- void
- ConditionNotify(Condition *condition) {
- Condition *c = condition;
- pthread_mutex_lock(&c->mutex);
- c->signaled = true;
- pthread_cond_signal(&c->cond);
- pthread_mutex_unlock(&c->mutex);
- }
- /*
- 下面是使用示例
- */
- void *
- Thread1(void *arg) {
- Condition *cond = arg;
- printf("thread1 waiting....\n");
- ConditionWait(cond);
- printf("thread1 end\n");
- return NULL;
- }
- void *
- Thread2(void *arg) {
- Condition *cond = arg;
- printf("thread2 notify....\n");
- ConditionNotify(cond);
- printf("thread2 end\n");
- return NULL;
- }
- /*
- 这里 thread1 会等到 thread2 notify 之后才会结束
- */
- int main(void) {
- Condition *cond = ConditionNew();
- pthread_t tid1;
- pthread_create(&tid1, NULL, Thread1, cond);
- pthread_t tid2;
- pthread_create(&tid2, NULL, Thread2, cond);
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement