目录
前言
1.条件变量
1.1应用场景:
生产者消费者问题,是线程同步的一种手段。
必要性:为了实现等待某个资源,让线程休眠。提高运行效率
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);
1.2使用步骤:
1.2.1初始化:
静态初始化
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
或使用动态初始化
pthread_cond_init(&cond);
1.2.2生产资源线程:
pthread_mutex_lock(&mutex);
开始产生资源
pthread_cond_sigal(&cond); //通知一个消费线程
或者
pthread_cond_broadcast(&cond); //广播通知多个消费线程
pthread_mutex_unlock(&mutex);
1.2.3消费者线程:
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 和 pthread_mutex_lock 必须配对使用。
2 如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。
3 pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。
注意 消费者的while(Head == NULL)的条件判断,带条件判断与不带条件判断的结果有点意思,这里理解有些困难,再琢磨琢磨
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
pthread_cond_t hasTaxi = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
struct taxi {
struct taxi *next;
int num;
};
struct taxi *Head = NULL;
//生产者
void* taxiproduct(void *arg){
printf("taxiproduct\n");
struct taxi *tx;
int i = 1;
while(1){
tx = malloc(sizeof(struct taxi));
tx->num = i++;
printf("taxi_id=%d\n",tx->num);
pthread_mutex_lock(&mutex);
tx->next = Head;
Head = tx;
//通知有车
//pthread_cond_signal(&hasTaxi);
pthread_cond_broadcast(&hasTaxi);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit("");
}
//消费者
void* taketaxi(void *arg){
printf("take taxi ready\n");
struct taxi *tx;
while(1){
pthread_mutex_lock(&mutex);
while(Head == NULL)
{
pthread_cond_wait(&hasTaxi,&mutex);
}
tx = Head;
Head = tx->next;
printf("%d,take taxi %d\n",(int)arg,tx->num);
free(tx);
pthread_mutex_unlock(&mutex);
}
pthread_exit("");
}
int main(int argc, const char *argv[])
{
pthread_t tid01,tid02;
pthread_create(&tid01,NULL,taxiproduct,NULL);
sleep(5);
pthread_create(&tid02,NULL,taketaxi,(void*)1);
pthread_create(&tid02,NULL,taketaxi,(void*)2);
pthread_create(&tid02,NULL,taketaxi,(void*)3);
//pthread_join(tid01,NULL);
//pthread_join(tid02,NULL);
while(1){
sleep(10);
}
return 0;
}
1.2.4 线程池概念和使用
概念:
通俗的讲就是一个线程的池子,可以循环的完成任务的一组线程集合
必要性:
我们平时创建一个线程,完成某一个任务,等待线程的退出。但当需要创建大量的线程时,假设T1为创建线程时间,T2为在线程任务执行时间,T3为线程销毁时间,当 T1+T3 > T2,这时候就不划算了,使用线程池可以降低频繁创建和销毁线程所带来的开销,任务处理时间比较短的时候这个好处非常显著。
1.2.5 线程池的基本结构:
1 任务队列,存储需要处理的任务,由工作线程来处理这些任务
2 线程池工作线程,它是任务队列任务的消费者,等待新任务的信号
1.2.6 线程池的实现:
1.创建线程池的基本结构:
任务队列链表
typedef struct Task;
线程池结构体
typedef struct ThreadPool;
2. 线程池的初始化:
pool_init()
{
创建一个线程池结构
实现任务队列互斥锁和条件变量的初始化
创建n个工作线程
}
3.线程池添加任务
pool_add_task()
{
判断是否有空闲的工作线程
给任务队列添加一个节点
给工作线程发送信号newtask
}
4实现工作线程
workThread()
{
while(1){
等待newtask任务信号
从任务队列中删除节点
执行任务
}
}
5.线程池的销毁
pool_destory()
{
删除任务队列链表所有节点,释放空间
删除所有的互斥锁条件变量
删除线程池,释放空间
}
编译错误:
error: ‘ThreadPool {aka struct ThreadPool}’ has no member named ‘head’
意义:ThreadPool 结构体没有head这个成员。
解决:检查是否拼写错误。
error: too few arguments to function ‘pthread_mutex_init’
意思:pthread_mutex_init这个函数参数少了
解决:检查函数的参数,添加对应的参数
3.线程的GDB调试:
3.1显示线程
info thread
3.2切换线程
thread id
3.3GDB为特定线程设置断点
break location thread id
3.4GDB设置线程锁
set scheduler-locking on/off
on:其他线程会暂停。可以单独调试一个线程
作业:
线程池创建
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#define POOL_NUM 10
//任务队列
typedef struct Task{
void*(*func)(void*arg);//函数指针-任务函数
void* arg;
struct Task *next;//链式栈
}Task;
typedef struct ThreadPool{
pthread_mutex_t taskLock;
pthread_cond_t newTask;
pthread_t tid[POOL_NUM];
struct Task *queue_head;
int busywork;
}ThreadPool;
ThreadPool *pool;
//任务
void* realwork(void*arg){
printf("任务%d\n",(int)arg);
}
//添加任务
void pool_add_task(void *arg){
Task *newTaskWork;
//判断有无空闲工作线程
pthread_mutex_lock(&pool->taskLock);
while(pool->busywork >= POOL_NUM){
pthread_mutex_unlock(&pool->taskLock);
usleep(10000);
pthread_mutex_lock(&pool->taskLock);
}
pthread_mutex_unlock(&pool->taskLock);
//
newTaskWork = malloc(sizeof(Task));
newTaskWork->func = realwork;
newTaskWork->arg = arg;
pthread_mutex_lock(&pool->taskLock);
if(pool->queue_head == NULL){
pool->queue_head = newTaskWork;
}else{
Task *temp = pool->queue_head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newTaskWork;
}
pool->busywork++;
pthread_cond_signal(&pool->newTask);
pthread_mutex_unlock(&pool->taskLock);
}
//工作线程工作
void*workThread(void*arg){
while(1){
pthread_mutex_lock(&pool->taskLock);
//等待任务
pthread_cond_wait(&pool->newTask,&pool->taskLock);
Task *ptask = pool->queue_head;
pool->queue_head = pool->queue_head->next;
pthread_mutex_unlock(&pool->taskLock);
//任务执行完毕
ptask->func(ptask->arg);
pool->busywork--;//工作线程空闲
}
}
//销毁
void pool_destory(){
Task *head;
while(pool->queue_head != NULL){
head = pool->queue_head;
pool->queue_head->next = pool->queue_head;
free(head);
}
pthread_mutex_destroy(&pool->taskLock);
pthread_cond_destroy(&pool->newTask);
/*
int i;
for(i = 0;i <POOL_NUM;i++){
pthread_join(tid[i],NULL);
}
*/
}
//初始化
void pool_init(){
pool = malloc(sizeof(ThreadPool));
pthread_mutex_init(&pool->taskLock,NULL);
pthread_cond_init(&pool->newTask,NULL);
pool->queue_head = NULL;
pool->busywork = 0;
int i;
for(i = 0;i <POOL_NUM;i++){
pthread_create(&pool->tid[i],NULL,workThread,NULL);
}
}
int main(int argc, const char *argv[])
{
pool_init();
sleep(1);
int i;
for(i = 1;i <=20;i++){
pool_add_task((void*)i);
}
sleep(10);
pool_destory();
return 0;
}