条件变量
应用场景:生产者消费者问题,是线程同步的一种手段。
必要性:为了实现等待某个资源,让线程休眠。提高运行效率
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);//等待资源
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);//等待资源一段时间就退出
int pthread_cond_signal(pthread_cond_t *cond);//通知一个消费线程
int pthread_cond_broadcast(pthread_cond_t *cond);//广播通知多个消费线程
使用步骤:
初始化:
静态初始化
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
或使用动态初始化
pthread_cond_init(&cond);
生产资源线程:
pthread_mutex_lock(&mutex);
开始产生资源
pthread_cond_sigal(&cond); //通知一个消费线程
或者
pthread_cond_broadcast(&cond); //广播通知多个消费线程
pthread_mutex_unlock(&mutex);
消费者线程:
pthread_mutex_lock(&mutex);
while (如果没有资源){ //防止惊群效应
pthread_cond_wait(&cond, &mutex);
}
有资源了,消费资源
pthread_mutex_unlock(&mutex);
注意:
1 pthread_cond_wait(&cond, &mutex),在没有资源等待是是先unlock 休眠,等资源到了,再lock
所以pthread_cond_wait he pthread_mutex_lock 必须配对使用。
2 如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。
3 pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
pthread_cond_t hasTaxi = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct taxi
{
struct taxi* next;
int num;
};
struct taxi* Head = NULL;
void* taxiarv(void* arg)
{
printf("taxi arrived thread\n");
pthread_detach(pthread_self());
struct taxi* tx;
int i = 1;
while (1)
{
tx = malloc(sizeof(struct taxi));
tx->num = i++;
printf("taxi %d comming\n", tx->num);
pthread_mutex_lock(&lock);
tx->next = Head;
Head = tx;
pthread_cond_signal(&hasTaxi);
//pthread_cond_broadcast(&hasTaxi);
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit(0);
}
void* takeTaxi(void* arg)
{
printf("take taxi thread\n");
pthread_detach(pthread_self());//将一个线程设置为分离状态,使得该线程结束后,系统可以自动回收其所占用的资源,而无需其他线程调用pthread_join函数来等待该线程结束。
struct taxi* tx;
while (1)
{
pthread_mutex_lock(&lock);
while (Head == NULL)
{
pthread_cond_wait(&hasTaxi, &lock);
}
tx = Head;
Head = tx->next;
printf("%d,Take taxi %d\n", (int)arg, tx->num);
free(tx);
pthread_mutex_unlock(&lock);
}
pthread_exit(0);
}
int main()
{
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, taxiarv, NULL);
// sleep(5);
pthread_create(&tid2, NULL, takeTaxi, (void*)1);
pthread_create(&tid2, NULL, takeTaxi, (void*)2);
pthread_create(&tid2, NULL, takeTaxi, (void*)3);
while (1)
{
sleep(1);
}
}
链表需不需要头部指针
链表不一定需要头部指针,具体是否需要头部指针取决于链表的设计和使用场景。
在某些情况下,头部指针是必需的,因为它用于指向链表的起始位置,方便对整个链表的操作。头部指针可以简化对链表的插入、删除和遍历等操作。例如,在双向链表中,头部指针通常用于指向链表的第一个节点,这样可以方便地在头部插入新节点。
然而,在其他情况下,头部指针并不是必需的。例如,如果只需要对链表进行顺序访问,不需要在头部插入或删除节点,那么不使用头部指针也是可行的。此时,可以使用一个临时指针来指向链表的第一个节点,从而完成链表的遍历操作。
总结来说,是否需要头部指针取决于链表的具体需求和使用场景。需要根据具体情况来设计和选择是否使用头部指针。