pthread_cond_t

2022-10-16

条件锁pthread_cond_t

(1)pthread_cond_wait的使用

等待线程
1. 使用pthread_cond_wait前要先加锁
2. pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
3. pthread_cond_wait被激活后会再自动加锁

(2)pthread_cond_signal的使用

激活线程:
1. 加锁(和等待线程用同一个锁)
2. pthread_cond_signal发送信号
3. 解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>struct msg {
struct msg* next;
int data;
};
struct msg* tasks = NULL; pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* TestWait(void* args) {
pthread_mutex_lock(&mu);//这里开始时加锁
while() {
pthread_cond_wait(&cond, &mu);//该函数首先将当前线程加入内部的等待列表中,然后释放锁,接着休眠并阻塞。。。。。直到有外部信号(pthread_cond_signal)通知,会加锁然后返回。
printf("%ld wake up\n", pthread_self());
if (tasks != NULL) {
struct msg* tsk = tasks;
tasks = tasks->next;
printf("tid:%ld data:%ld\n", pthread_self(), tsk->data);
free(tsk);
}
}
pthread_mutex_unlock(&mu);
pthread_exit(NULL);
} int main() { pthread_t tids[];
for(int i = ; i < ; i++) {
pthread_create(&tids[i], NULL, TestWait, NULL);
}
sleep(); for (int i = ; i < ; i++) {
pthread_mutex_lock(&mu); struct msg* tmp = (struct msg*) malloc(sizeof(struct msg));
tmp->next = tasks;
tmp->data = ;
tasks = tmp; pthread_cond_signal(&cond);
//pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mu);
} pthread_exit(NULL);
return ;
}

pthread_cond_t的相关教程结束。

《pthread_cond_t.doc》

下载本文的Word格式文档,以方便收藏与打印。