Linux网络学习 第五天

目录

内容回顾

学习目标

线程池

UDP通信

本地socket通信

内容回顾

poll

输入和输出分离, 输入用events, 输出用revents

epoll

ET模式是写一次通知一次, 若写的数据多, 读的数据少, 则不会再通知, 直到下一次有写事件发生.

思考题? epoll监控监听文件描述符可以设置成ET模式吗??

答案: 可以. 但是如果设置成ET模式以后, 当调用epoll_wait函数的时候, 每次只能accept一个连接(该连接在已连接队列当中, 而调用一次accept只能已连接队列中获取一个连接), 如果同时有多个连接到来, 就得epoll_wait再次返回之后才能继续accept下一个连接, 所以如果设置成了ET模式且有多个连接请求的话, 应该将accept写在循环当中, 一次epoll_wait后循环accept所有的连接.

所以一般不会在epoll中将监听的文件描述符设置为ET模式, 使用默认的LT模式即可; 而对通信的文件描述符一般采用非阻塞模式的ET模式.

学习目标

  • 了解线程池模型的设计思想
  • 能看懂线程池实现源码
  • 掌握tcp 和udp 的优缺点和使用场景
  • 说出udp 服务器通信流程
  • 说出udp 客户端通信流程
  • 独立实现udp 服务器代码
  • 独立实现udp 客户端代码
  • 熟练掌握本地套接字进行本地进程通信

线程池

什么是线程池?

是一个抽象的概念, 若干个线程组合到一起, 形成线程池.

为什么需要线程池?

多线程版服务器一个客户端就需要创建一个线程! 若客户端太多, 显然不太合适.

什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。

实现的时候类似于生产者和消费者.

线程池和任务池:

任务池相当于共享资源, 所以需要使用互斥锁, 当任务池中没有任务的时候需要让线程阻塞, 所以需要使用条件变量.

Linux网络学习 第五天

线程池思想

Linux网络学习 第五天

线程池代码分析

如何让线程执行不同的任务?

使用回到函数, 在任务中设置任务执行函数, 这样可以起到不同的任务执行不同的函数.

通过阅读线程池代码思考如下问题?

  • 熟悉结构体 threadpool_t
  • 线程池如何创建起来? 各种初始化,malloc,pthread_create,pthread_cond_init pthread_mutex_init
  • 线程池内都有几类线程? 2类:管理线程+工作线程
  • 管理者线程的任务是什么?任务如何实现? 任务是添加线程或者删除线程,通过2个算法,删除线程 wait_exit_thr_num = 10
  • 工作线程如何工作? 等待有任务,抢到任务,修改busy_thr_num ++ 执行任务 修改 busy_thr_num —
  • 线程池是如何销毁的? 自爆shutdown 诱杀!

讲解代码threadpoolsimple.c

threadpoolsimple为简洁版的线程池版本,通过模仿队列的方式实现线程池

Linux网络学习 第五天

threadpoolsimple.c代码分析

#ifndef _THREADPOOL_H
#define _THREADPOOL_H

#include
#include
#include
#include
#include
#include

typedef struct _PoolTask
{
    int tasknum;                  // 模拟任务编号
    void *arg;                    // 回调函数参数
    void (*task_func)(void *arg); // 任务的回调函数
} PoolTask;

typedef struct _ThreadPool
{
    int max_job_num; // 最大任务个数
    int job_num;     // 实际任务个数
    PoolTask *tasks; // 任务队列数组
    int job_push;    // 入队位置
    int job_pop;     // 出队位置

    int thr_num;                   // 线程池内线程个数
    pthread_t *threads;            // 线程池内线程数组
    int shutdown;                  // 是否关闭线程池
    pthread_mutex_t pool_lock;     // 线程池的锁
    pthread_cond_t empty_task;     // 任务队列为空的条件
    pthread_cond_t not_empty_task; // 任务队列不为空的条件

} ThreadPool;

void create_threadpool(int thrnum, int maxtasknum); // 创建线程池--thrnum  代表线程个数,maxtasknum 最大任务个数
void destroy_threadpool(ThreadPool *pool);          // 摧毁线程池
void addtask(ThreadPool *pool);                     // 添加任务到线程池
void taskRun(void *arg);                            // 任务回调函数

#endif //_THREADPOOL_H
// 简易版线程池
#include "threadpoolsimple.h"

ThreadPool *thrPool = NULL;

int beginnum = 1000;

void *thrRun(void *arg)
{
    // printf("begin call %s-----\n",__FUNCTION__);
    ThreadPool *pool = (ThreadPool *)arg;
    int taskpos = 0; // 任务位置
    PoolTask *task = (PoolTask *)malloc(sizeof(PoolTask));

    while (1)
    {
        // 获取任务,先要尝试加锁
        pthread_mutex_lock(&thrPool->pool_lock);

        // 无任务并且线程池不是要摧毁
        while (thrPool->job_num shutdown)
        {
            // 如果没有任务,线程会阻塞
            pthread_cond_wait(&thrPool->not_empty_task, &thrPool->pool_lock);
        }

        if (thrPool->job_num)
        {
            // 有任务需要处理
            taskpos = (thrPool->job_pop++) % thrPool->max_job_num;
            // printf("task out %d...tasknum===%d tid=%lu\n",taskpos,thrPool->tasks[taskpos].tasknum,pthread_self());
            // 为什么要拷贝?避免任务被修改,生产者会添加任务
            memcpy(task, &thrPool->tasks[taskpos], sizeof(PoolTask));
            task->arg = task;
            thrPool->job_num--;
            // task = &thrPool->tasks[taskpos];
            pthread_cond_signal(&thrPool->empty_task); // 通知生产者
        }

        if (thrPool->shutdown)
        {
            // 代表要摧毁线程池,此时线程退出即可
            // pthread_detach(pthread_self());//临死前分家
            pthread_mutex_unlock(&thrPool->pool_lock);
            free(task);
            pthread_exit(NULL);
        }

        // 释放锁
        pthread_mutex_unlock(&thrPool->pool_lock);
        task->task_func(task->arg); // 执行回调函数
    }

    // printf("end call %s-----\n",__FUNCTION__);
}

// 创建线程池
void create_threadpool(int thrnum, int maxtasknum)
{
    printf("begin call %s-----\n", __FUNCTION__);
    thrPool = (ThreadPool *)malloc(sizeof(ThreadPool));

    thrPool->thr_num = thrnum;
    thrPool->max_job_num = maxtasknum;
    thrPool->shutdown = 0; // 是否摧毁线程池,1代表摧毁
    thrPool->job_push = 0; // 任务队列添加的位置
    thrPool->job_pop = 0;  // 任务队列出队的位置
    thrPool->job_num = 0;  // 初始化的任务个数为0

    thrPool->tasks = (PoolTask *)malloc((sizeof(PoolTask) * maxtasknum)); // 申请最大的任务队列

    // 初始化锁和条件变量
    pthread_mutex_init(&thrPool->pool_lock, NULL);
    pthread_cond_init(&thrPool->empty_task, NULL);
    pthread_cond_init(&thrPool->not_empty_task, NULL);

    int i = 0;
    thrPool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thrnum); // 申请n个线程id的空间

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    for (i = 0; i < thrnum; i++)
    {
        pthread_create(&thrPool->threads[i], &attr, thrRun, (void *)thrPool); // 创建多个线程
    }
    // printf("end call %s-----\n",__FUNCTION__);
}
// 摧毁线程池
void destroy_threadpool(ThreadPool *pool)
{
    pool->shutdown = 1;                            // 开始自爆
    pthread_cond_broadcast(&pool->not_empty_task); // 诱杀

    int i = 0;
    for (i = 0; i < pool->thr_num; i++)
    {
        pthread_join(pool->threads[i], NULL);
    }

    pthread_cond_destroy(&pool->not_empty_task);
    pthread_cond_destroy(&pool->empty_task);
    pthread_mutex_destroy(&pool->pool_lock);

    free(pool->tasks);
    free(pool->threads);
    free(pool);
}

// 添加任务到线程池
void addtask(ThreadPool *pool)
{
    // printf("begin call %s-----\n",__FUNCTION__);
    pthread_mutex_lock(&pool->pool_lock);

    // 实际任务总数大于最大任务个数则阻塞等待(等待任务被处理)
    while (pool->max_job_num job_num)
    {
        pthread_cond_wait(&pool->empty_task, &pool->pool_lock);
    }

    int taskpos = (pool->job_push++) % pool->max_job_num;
    // printf("add task %d  tasknum===%d\n",taskpos,beginnum);
    pool->tasks[taskpos].tasknum = beginnum++;
    pool->tasks[taskpos].arg = (void *)&pool->tasks[taskpos];
    pool->tasks[taskpos].task_func = taskRun;
    pool->job_num++;

    pthread_mutex_unlock(&pool->pool_lock);

    pthread_cond_signal(&pool->not_empty_task); // 通知包身工
    // printf("end call %s-----\n",__FUNCTION__);
}

// 任务回调函数
void taskRun(void *arg)
{
    PoolTask *task = (PoolTask *)arg;
    int num = task->tasknum;
    printf("task %d is runing %lu\n", num, pthread_self());

    sleep(1);
    printf("task %d is done %lu\n", num, pthread_self());
}

int main()
{
    create_threadpool(3, 20);
    int i = 0;
    for (i = 0; i < 50; i++)
    {
        addtask(thrPool); // 模拟添加任务
    }

    sleep(20);
    destroy_threadpool(thrPool);

    return 0;
}

讲解代码 pthreadpool.c

pthreadpool.c为上面线程的加强版本,使用了线程来管理线程池,当空闲线程较多的时候释放线程,当任务量多的时候进行添加线程。

Linux网络学习 第五天

pthreadpool.c代码分析

#ifndef __THREADPOOL_H_
#define __THREADPOOL_H_

typedef struct threadpool_t threadpool_t;

/**
 * @function threadpool_create
 * @descCreates a threadpool_t object.

 * @param thr_num  thread num
 * @param max_thr_num  max thread size
 * @param queue_max_size   size of the queue.

 * @return a newly created thread pool or NULL
 */
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);

/**
 * @function threadpool_add
 * @desc add a new task in the queue of a thread pool
 * @param pool     Thread pool to which add the task.

 * @param function Pointer to the function that will perform the task.

 * @param argument Argument to be passed to the function.

 * @return 0 if all goes well,else -1
 */
int threadpool_add(threadpool_t *pool, void *(*function)(void *arg), void *arg);

/**
 * @function threadpool_destroy
 * @desc Stops and destroys a thread pool.

 * @param pool  Thread pool to destroy.

 * @return 0 if destory success else -1
 */
int threadpool_destroy(threadpool_t *pool);

/**
 * @desc get the thread num
 * @pool pool threadpool
 * @return # of the thread
 */
int threadpool_all_threadnum(threadpool_t *pool);

/**
 * desc get the busy thread num
 * @param pool threadpool
 * return # of the busy thread
 */
int threadpool_busy_threadnum(threadpool_t *pool);

#endif
#include
#include
#include
#include
#include
#include
#include
#include
#include "threadpool.h"

#define DEFAULT_TIME 10                 /*10s检测一次*/
#define MIN_WAIT_TASK_NUM 10            /*如果queue_size > MIN_WAIT_TASK_NUM 添加新的线程到线程池*/
#define DEFAULT_THREAD_VARY 10          /*每次创建和销毁线程的个数*/
#define true 1
#define false 0

typedef struct
{
    void *(*function)(void *);          /* 函数指针,回调函数 */
    void *arg;                          /* 上面函数的参数 */
} threadpool_task_t;                    /* 各子线程任务结构体 */

/* 描述线程池相关信息 */
struct threadpool_t
{
    pthread_mutex_t lock;               /* 用于锁住本结构体 */
    pthread_mutex_t thread_counter;     /* 记录忙状态线程个数de琐 -- busy_thr_num */

    pthread_cond_t queue_not_full;      /* 当任务队列满时,添加任务的线程阻塞,等待此条件变量 */
    pthread_cond_t queue_not_empty;     /* 任务队列里不为空时,通知等待任务的线程 */

    pthread_t *threads;                 /* 存放线程池中每个线程的tid。数组 */
    pthread_t adjust_tid;               /* 存管理线程tid */
    threadpool_task_t *task_queue;      /* 任务队列(数组首地址) */

    int min_thr_num;                    /* 线程池最小线程数 */
    int max_thr_num;                    /* 线程池最大线程数 */
    int live_thr_num;                   /* 当前存活线程个数 */
    int busy_thr_num;                   /* 忙状态线程个数 */
    int wait_exit_thr_num;              /* 要销毁的线程个数 */

    int queue_front;                    /* task_queue队头下标 */
    int queue_rear;                     /* task_queue队尾下标 */
    int queue_size;                     /* task_queue队中实际任务数 */
    int queue_max_size;                 /* task_queue队列可容纳任务数上限 */

    int shutdown;                       /* 标志位,线程池使用状态,true或false */
};

void *threadpool_thread(void *threadpool);

void *adjust_thread(void *threadpool);

int is_thread_alive(pthread_t tid);
int threadpool_free(threadpool_t *pool);

//threadpool_create(3,100,100);
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size)
{
    int i;
    threadpool_t *pool = NULL;
    do
    {
        if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL)
        {
            printf("malloc threadpool fail");
            break;                                      /*跳出do while*/
        }

        pool->min_thr_num = min_thr_num;
        pool->max_thr_num = max_thr_num;
        pool->busy_thr_num = 0;
        pool->live_thr_num = min_thr_num;               /* 活着的线程数 初值=最小线程数 */
        pool->wait_exit_thr_num = 0;
        pool->queue_size = 0;                           /* 有0个产品 */
        pool->queue_max_size = queue_max_size;
        pool->queue_front = 0;
        pool->queue_rear = 0;
        pool->shutdown = false;                         /* 不关闭线程池 */

        /* 根据最大线程上限数, 给工作线程数组开辟空间, 并清零 */
        pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
        if (pool->threads == NULL)
        {
            printf("malloc threads fail");
            break;
        }
        memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num);

        /* 队列开辟空间 */
        pool->task_queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size);
        if (pool->task_queue == NULL)
        {
            printf("malloc task_queue fail\n");
            break;
        }

        /* 初始化互斥琐、条件变量 */
        if (pthread_mutex_init(&(pool->lock), NULL) != 0
                || pthread_mutex_init(&(pool->thread_counter), NULL) != 0
                || pthread_cond_init(&(pool->queue_not_empty), NULL) != 0
                || pthread_cond_init(&(pool->queue_not_full), NULL) != 0)
        {
            printf("init the lock or cond fail\n");
            break;
        }

        //启动工作线程
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
        for (i = 0; i < min_thr_num; i++)
        {
            pthread_create(&(pool->threads[i]), &attr, threadpool_thread, (void *)pool);/*pool指向当前线程池*/
            printf("start thread 0x%x...\n", (unsigned int)pool->threads[i]);
        }

        //创建管理者线程
        pthread_create(&(pool->adjust_tid), &attr, adjust_thread, (void *)pool);

        return pool;

    } while (0);

    /* 前面代码调用失败时,释放poll存储空间 */
    threadpool_free(pool);

    return NULL;
}

/* 向线程池中 添加一个任务 */
//threadpool_add(thp, process, (void*)&num[i]);   /* 向线程池中添加任务 process: 小写---->大写*/

int threadpool_add(threadpool_t *pool, void*(*function)(void *arg), void *arg)
{
    pthread_mutex_lock(&(pool->lock));

    /* ==为真,队列已经满, 调wait阻塞 */
    while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown))
    {
        pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));
    }

    if (pool->shutdown)
    {
        pthread_cond_broadcast(&(pool->queue_not_empty));
        pthread_mutex_unlock(&(pool->lock));
        return 0;
    }

    /* 清空 工作线程 调用的回调函数 的参数arg */
    if (pool->task_queue[pool->queue_rear].arg != NULL)
    {
        pool->task_queue[pool->queue_rear].arg = NULL;
    }

    /*添加任务到任务队列里*/
    pool->task_queue[pool->queue_rear].function = function;
    pool->task_queue[pool->queue_rear].arg = arg;
    pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size;       /* 队尾指针移动, 模拟环形 */
    pool->queue_size++;

    /*添加完任务后,队列不为空,唤醒线程池中 等待处理任务的线程*/
    pthread_cond_signal(&(pool->queue_not_empty));
    pthread_mutex_unlock(&(pool->lock));

    return 0;
}

/* 线程池中各个工作线程 */
void *threadpool_thread(void *threadpool)
{
    threadpool_t *pool = (threadpool_t *)threadpool;
    threadpool_task_t task;

    while (true)
    {
        /* Lock must be taken to wait on conditional variable */
        /*刚创建出线程,等待任务队列里有任务,否则阻塞等待任务队列里有任务后再唤醒接收任务*/
        pthread_mutex_lock(&(pool->lock));

        /*queue_size == 0 说明没有任务,调 wait 阻塞在条件变量上, 若有任务,跳过该while*/
        while ((pool->queue_size == 0) && (!pool->shutdown))
        {
            printf("thread 0x%x is waiting\n", (unsigned int)pthread_self());
            pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));//暂停到这

            /*清除指定数目的空闲线程,如果要结束的线程个数大于0,结束线程*/
            /*没有任务量的时候对线程进行清理 清理指定的线程个数*/
            if (pool->wait_exit_thr_num > 0)
            {
                pool->wait_exit_thr_num--;

                /*如果线程池里线程个数大于最小值时可以结束当前线程*/
                if (pool->live_thr_num > pool->min_thr_num)
                {
                    printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
                    pool->live_thr_num--;
                    pthread_mutex_unlock(&(pool->lock));
                    //pthread_detach(pthread_self());
                    pthread_exit(NULL);
                }
            }
        }

        /*如果指定了true,要关闭线程池里的每个线程,自行退出处理---销毁线程池*/
        if (pool->shutdown)
        {
            pthread_mutex_unlock(&(pool->lock));
            printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
            //pthread_detach(pthread_self());
            pthread_exit(NULL);     /* 线程自行结束 */
        }

        /*从任务队列里获取任务, 是一个出队操作*/
        task.function = pool->task_queue[pool->queue_front].function;
        task.arg = pool->task_queue[pool->queue_front].arg;

        pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size;       /* 出队,模拟环形队列 */
        pool->queue_size--;

        /*通知可以有新的任务添加进来*/
        pthread_cond_broadcast(&(pool->queue_not_full));

        /*任务取出后,立即将 线程池琐 释放*/
        pthread_mutex_unlock(&(pool->lock));

        /*执行任务*/
        printf("thread 0x%x start working\n", (unsigned int)pthread_self());
        pthread_mutex_lock(&(pool->thread_counter));                            /*忙状态线程数变量琐*/
        pool->busy_thr_num++;                                                   /*忙状态线程数+1*/
        pthread_mutex_unlock(&(pool->thread_counter));

        (*(task.function))(task.arg);                                           /*执行回调函数任务 不取引用获取的是指针,执行需要加*进行解引用*/
        //task.function(task.arg);                                              /*执行回调函数任务*/

        /*任务结束处理*/
        printf("thread 0x%x end working\n", (unsigned int)pthread_self());
        pthread_mutex_lock(&(pool->thread_counter));
        pool->busy_thr_num--;                                       /*处理掉一个任务,忙状态数线程数-1*/
        pthread_mutex_unlock(&(pool->thread_counter));
    }

    pthread_exit(NULL);
}

/* 管理线程 */
void *adjust_thread(void *threadpool)
{
    int i;
    threadpool_t *pool = (threadpool_t *)threadpool;
    while (!pool->shutdown)
    {

        sleep(DEFAULT_TIME);                                    /*定时 对线程池管理*/

        pthread_mutex_lock(&(pool->lock));
        int queue_size = pool->queue_size;                      /* 关注 任务数 */
        int live_thr_num = pool->live_thr_num;                  /* 存活 线程数 */
        pthread_mutex_unlock(&(pool->lock));

        pthread_mutex_lock(&(pool->thread_counter));
        int busy_thr_num = pool->busy_thr_num;                  /* 忙着的线程数 */
        pthread_mutex_unlock(&(pool->thread_counter));

        /* 创建新线程 算法: 任务数大于最小线程池个数, 且存活的线程数少于最大线程个数时 如:30>=10 && 40= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num)
        {
            pthread_mutex_lock(&(pool->lock));
            int add = 0;

            /*一次增加 DEFAULT_THREAD 个线程*/
            /* 当线程不存活的时候创建新的线程 add索引用于区别创建线程的个数 i用于找到那些被销毁的线程索引 */
            for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY
                    && pool->live_thr_num < pool->max_thr_num; i++)
            {
                if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i]))
                {
                    pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
                    add++;
                    pool->live_thr_num++;
                }
            }

            pthread_mutex_unlock(&(pool->lock));
        }

        /* 销毁多余的空闲线程 算法:忙线程X2 小于 存活的线程数 且 存活的线程数 大于 最小线程数时*/
        if ((busy_thr_num * 2) < live_thr_num  &&  live_thr_num > pool->min_thr_num)
        {
            /* 一次销毁DEFAULT_THREAD个线程, 隨機10個即可 */
            pthread_mutex_lock(&(pool->lock));
            pool->wait_exit_thr_num = DEFAULT_THREAD_VARY;      /* 要销毁的线程数 设置为10 */
            pthread_mutex_unlock(&(pool->lock));

            for (i = 0; i < DEFAULT_THREAD_VARY; i++)
            {
                /* 通知处在空闲状态的线程, 他们会自行终止*/
                pthread_cond_signal(&(pool->queue_not_empty));
            }
        }
    }

    return NULL;
}

int threadpool_destroy(threadpool_t *pool)
{
    int i;
    if (pool == NULL)
    {
        return -1;
    }
    pool->shutdown = true;

    /*先销毁管理线程*/
    //pthread_join(pool->adjust_tid, NULL);

    for (i = 0; i < pool->live_thr_num; i++)
    {
        /*通知所有的空闲线程*/
        pthread_cond_broadcast(&(pool->queue_not_empty));
    }

    /*for (i = 0; i < pool->live_thr_num; i++)
    {
        pthread_join(pool->threads[i], NULL);
    }*/

    threadpool_free(pool);

    return 0;
}

int threadpool_free(threadpool_t *pool)
{
    if (pool == NULL)
    {
        return -1;
    }

    if (pool->task_queue)
    {
        free(pool->task_queue);
    }

    if (pool->threads)
    {
        free(pool->threads);
        pthread_mutex_lock(&(pool->lock));
        pthread_mutex_destroy(&(pool->lock));
        pthread_mutex_lock(&(pool->thread_counter));
        pthread_mutex_destroy(&(pool->thread_counter));
        pthread_cond_destroy(&(pool->queue_not_empty));
        pthread_cond_destroy(&(pool->queue_not_full));
    }

    free(pool);
    pool = NULL;

    return 0;
}

int threadpool_all_threadnum(threadpool_t *pool)
{
    int all_threadnum = -1;

    pthread_mutex_lock(&(pool->lock));
    all_threadnum = pool->live_thr_num;
    pthread_mutex_unlock(&(pool->lock));

    return all_threadnum;
}

int threadpool_busy_threadnum(threadpool_t *pool)
{
    int busy_threadnum = -1;

    pthread_mutex_lock(&(pool->thread_counter));
    busy_threadnum = pool->busy_thr_num;
    pthread_mutex_unlock(&(pool->thread_counter));

    return busy_threadnum;
}

int is_thread_alive(pthread_t tid)
{
    int kill_rc = pthread_kill(tid, 0);     //发0号信号,测试线程是否存活
    if (kill_rc == ESRCH)
    {
        return false;
    }

    return true;
}

/*测试*/

#if 1
/* 线程池中的线程,模拟处理业务 */
void *process(void *arg)
{
    printf("thread 0x%x working on task %d\n ",(unsigned int)pthread_self(),*(int *)arg);
    sleep(1);
    printf("task %d is end\n", *(int *)arg);

    return NULL;
}

int main(void)
{
    /*threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);*/
    threadpool_t *thp = threadpool_create(3,100,100);   /*创建线程池,池里最小3个线程,最大100,队列最大100*/
    printf("pool inited");

    //int *num = (int *)malloc(sizeof(int)*20);
    int num[20], i;
    for (i = 0; i < 20; i++)
    {
        num[i]=i;
        printf("add task %d\n",i);
        threadpool_add(thp, process, (void*)&num[i]);   /* 向线程池中添加任务 */
    }

    sleep(10);                                          /* 等子线程完成任务 */
    threadpool_destroy(thp);

    return 0;
}

#endif

/*
    main函数:
    创建线程,添加任务,销毁线程

    threadpool_create函数:
    首先初始化线程池 -->molloc申请空间 初始化线程组 任务(任务参数、任务回调函数)、
                    锁(线程池锁和忙碌线程锁)、互斥量(满和空)、队头队尾、最大最小队列(线程)、忙碌和空闲线程等
    设置分离线程模式,创建线程,设置回调函数threadpool_thread,将线程池作为变量传入回调函数中。
    创建管理线程的线程adjust_thread

    threadpool_thread如果没有任务不往下走,因此先看threadpool_add添加任务函数,参数为threadpool_t *pool, void*(*function)(void *arg), void *arg;
    首先加锁,判断是否已经达到最大线程或最大队列数,如果达到则thread_cont_wait进行阻塞,等执行完的时候再通知
    判断是否shotdown为ture,如果是释放线程资源,回收变量,否则清空之前任务量的void *arg参数,
    重新设置传入的参数,设置任务量时采用%max_thr_num实现循环数组。
    通知非空信号进行处理,后进行解锁。

    threadpool_thread执行时首先根据参数进行类型转换获取线程池对象,加锁操作,
    如果没有任务量且shotdown为false,则阻塞,阻塞后代码为释放线程资源,便于管理线程进行通知删除线程
    如果shotdown为true,则释放线程资源,取出任务量,队列长度--,广播通知队列为饱满,对忙碌线程进行加锁++,
    执行任务,对忙碌线程进行加锁--。

    adjust_thread函数负责管理线程,参数为线程池,利用定时器定期对线程池进行管理,通过加锁互斥量获取任务数、存活线程数和忙碌线程数
        创建新线程算法:任务量大于最小线程池个数且存活的线程少于最大的线程个数时进行添加线程
    添加线程时根据设置的DEFAULT_THREAD添加默认个线程,添加时下标从i=0开始一个一个遍历线程池,
    设置addnum=0计数,跳出循环条件为addnum

UDP通信

TCP:传输控制协议, 面向连接的,稳定的,可靠的,安全的数据流传递

稳定和可靠: 丢包重传

数据有序: 序号和确认序号

流量控制: 滑动窗口

UDP:用户数据报协议

面向无连接的,不稳定,不可靠,不安全的数据报传递—更像是收发短信

UDP传输不需要建立连接,传输效率更高,在稳定的局域网内环境相对可靠

//UDP通信相关函数介绍:
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                        struct sockaddr *src_addr, socklen_t *addrlen);
/*
函数说明: 接收消息
参数说明:
   sockfd 套接字
   buf  要接受的缓冲区
   len  缓冲区的长度
   flags 标志位 一般填0
   src_addr 原地址 传出参数
   addrlen  发送方地址长度
   返回值
成功: 返回读到的字节数
失败: 返回 -1 设置errno
      调用该函数相当于TCP通信的recv+accept函数
 */

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
                      const struct sockaddr *dest_addr, socklen_t addrlen);
/*
函数说明: 发送数据
参数说明:
   sockfd 套接字
   dest_addr 目的地址
   addrlen 目的地址长度
   返回值
成功: 返回写入的字节数
失败: 返回-1,设置errno
*/

Linux网络学习 第五天

UDP创建连接后,就算中间断开连接也不需要重新连接,直接发送数据即可。

UDP的服务器编码流程:

  • 创建套接字 type=SOCK_DGRAM

  • 绑定ip和端口

  • while(1)

{

收发消–recvfrom

发消息–sendto

}

  • 关闭套接字–close

UDP客户端流程:

  • 创建套接字–socket

  • while(1)

{

收发消–recvfrom

发消息–sendto

}

  • 关闭套接字–close

编写udp代码并进行测试

服务端 01-udp-server.c

#include
#include
#include
#include
#include
#include
#include
#include
#include

// tcp 客户端用 nc 127.1 888
// udp 客户端用 nc -u 127.1 8888
// netstat -anp | grep 8888查看链接 udp无

int main()
{
    // 创建Socekt tcp SOCK_STREAM udp SOCK_DGRAM
    int cfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (cfd < 1)
    {
        perror("socket error");
        return -1;
    }

    // 绑定socket
    struct sockaddr_in serv;
    struct sockaddr_in client;
    bzero(&serv, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8888);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(cfd, (struct sockaddr *)&serv, sizeof(serv));

    int n;
    char buf[1024];
    int i;
    socklen_t len;
    while (1)
    {
        // 接收数据
        memset(buf, 0x00, sizeof(buf));
        len = sizeof(serv);
        int n = recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len);

        if (n

客户端 02-udp-client.c

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

// tcp 客户端用 nc 127.1 888
// udp 客户端用 nc -u 127.1 8888
// netstat -anp | grep 8888查看链接 udp无

int main()
{
    // 创建Socekt tcp SOCK_STREAM udp SOCK_DGRAM
    int cfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (cfd < 1)
    {
        perror("socket error");
        return -1;
    }

    // 给socket辅赋值地址和端口号
    struct sockaddr_in serv;
    bzero(&serv, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8888);
    inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr.s_addr);

    int n;
    char buf[1024];
    int i;
    socklen_t len = sizeof(serv);
    while (1)
    {
        // 读标准输入数据
        memset(buf, 0x00, sizeof(buf));
        n = read(STDIN_FILENO, buf, sizeof(buf));
        sendto(cfd, buf, n, 0, (struct sockaddr *)&serv, len);

        // 接收数据
        memset(buf, 0x00, sizeof(buf));
        n = recvfrom(cfd, buf, sizeof(buf), 0, NULL, &len);
        printf("n==[%d], buf==[%s]\n", n, buf);
    }

    // 关闭通信描述符
    close(cfd);

    return 0;
}

测试:

多开器几个客户端经过测试表明:, udp天然支持多客户端, 这点和TCP不同, TCP需要维护连接.

使用nc命令进行测试: nc -u 127.1 8888

本地socket通信

回顾一些linux系统有哪些文件类型?

1、普通文件(regular file):就是一般存取的文件,由ls -al显示出来的属性中,第一个属性为 [-],例如 [-rwxrwxrwx]。另外,依照文件的内容,又大致可以分为:

2、纯文本文件(ASCII):这是Unix系统中最多的一种文件类型,之所以称为纯文本文件,是因为内容可以直接读到的数据,例如数字、字母等等。设 置文件几乎都属于这种文件类型。举例来说,使用命令”cat ~/.bashrc”就可以看到该文件的内容(cat是将文件内容读出来)。

3、二进制文件(binary):系统其实仅认识且可以执行二进制文件(binary file)。Linux中的可执行文件(脚本,文本方式的批处理文件不算)就是这种格式的。举例来说,命令cat就是一个二进制文件。

4、数据格式的文件(data):有些程序在运行过程中,会读取某些特定格式的文件,那些特定格式的文件可以称为数据文件(data file)。举例来说,Linux在用户登入时,都会将登录数据记录在 /var/log/wtmp文件内,该文件是一个数据文件,它能通过last命令读出来。但使用cat时,会读出乱码。因为它是属于一种特殊格式的文件。

目录文件(directory):就是目录,第一个属性为 [d],例如 [drwxrwxrwx]。

连接文件(link):类似Windows下面的快捷方式。第一个属性为 [l],例如 [lrwxrwxrwx]。

设备与设备文件(device):与系统外设及存储等相关的一些文件,通常都集中在 /dev目录。通常又分为两种:

块设备文件:就是存储数据以供系统存取的接口设备,简单而言就是硬盘。例如一号硬盘的代码是 /dev/hda1等文件。第一个属性为 [b]。

字符设备文件:即串行端口的接口设备,例如键盘、鼠标等等。第一个属性为 [c]。

套接字(sockets):这类文件通常用在网络数据连接。可以启动一个程序来监听客户端的要求,客户端就可以通过套接字来进行数据通信。第一个属性为 [s],最常在 /var/run目录中看到这种文件类型。

管道(FIFO,pipe):FIFO也是一种特殊的文件类型,它主要的目的是,解决多个程序同时存取一个文件所造成的错误。FIFO是first-in-first-out(先进先出)的缩写。第一个属性为 [p]。

回顾一些linux系统下有哪些常见的IPC机制?

Linux中主要的IPC机制有:管道(pipe)、信号(sinal)、信号量(semophore)、消息队列(Message)、共享内存(Share Memory)、套接字(Socket)等。

通过查询: man 7 unix 可以查到unix本地域socket通信相关信息:

#include

#include

int socket(int domain, int type, int protocol);

/*
函数说明: 创建本地域socket

函数参数:   

domain: AF_UNIX or AF_LOCAL

type: SOCK_STREAM或者SOCK_DGRAM

protocol: 0 表示使用默认协议

函数返回值:

成功: 返回文件描述符.

失败: 返回-1, 并设置errno值.

*/

创建socket成功以后, 会在内核创建缓冲区, 下图是客户端和服务端内核缓冲区示意图.

Linux网络学习 第五天
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
/*
函数说明: 绑定套接字
函数参数:
socket: 由socket函数返回的文件描述符
addr: 本地地址
addlen: 本地地址长度
函数返回值:
成功: 返回文件描述符.

失败: 返回-1, 并设置errno值.

Bind成功之后会创建一个文件,大小为0
*/

需要注意的是: bind函数会自动创建socket文件, 若在调用bind函数之前socket文件已经存在, 则调用bind会报错, 可以使用unlink函数在bind之前先删除文件.

struct sockaddr_un
{

    sa_family_t sun_family;  /* AF_UNIX or AF_LOCAL*/

    char sun_path[108];  /* pathname */

};

Linux网络学习 第五天

通过man 2 bind, 可以查看bind函数的相关信息, 后面还有示例代码, 可以参考.

本地套接字服务器的流程:

可以使用TCP的方式, 必须按照tcp的流程 ,也可以使用UDP的方式, 必须按照udp的流程

本地套接字只能在本地进行使用,在不同的电脑上不能通信处理

tcp的本地套接字服务器流程:

  • 创建套接字 socket(AF_UNIX,SOCK_STREAM,0)
  • 绑定 struct sockaddr_un &强转
  • 侦听 listen
  • 获得新连接 accept
  • 循环通信 read-write
  • 关闭文件描述符 close

tcp本地套接字客户端流程:

  • 调用socket创建套接字
  • 调用bind函数将socket文件描述和socket文件进行绑定.

不是必须的, 若无显示绑定会进行隐式绑定,但服务器不知道谁连接了.

  • 调用connect函数连接服务端
  • 循环通信read-write
  • 关闭文件描述符 close

编写代码并进行测试

测试客户端工具:

man nc

-U Specifies to use UNIX-domain sockets.

例如: nc -U sock.s

下面编写tcp协议的代码

服务器端03-unix-server.c

#include
#include
#include
#include
#include
#include
#include
#include
#include

int main()
{
    // 创建socket
    int lfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (lfd < 0)
    {
        perror("socket create error!");
        return -1;
    }

    // 删除sock文件 文件存在则以为端口还在占用
    unlink("serv.sock");

    // 绑定
    struct sockaddr_un serv;
    serv.sun_family = AF_UNIX;
    strcpy(serv.sun_path, "./serv.sock");
    int bindnum = bind(lfd, (struct sockaddr *)&serv, sizeof(serv));
    if (bindnum < 0)
    {
        perror("bind error!");
        return -1;
    }

    // 监听
    listen(lfd, 128);

    // 接收新的客户端连接
    struct sockaddr_un client;
    socklen_t len = sizeof(client);

    int cfd = accept(lfd, (struct sockaddr *)&client, &len);
    if (cfd < 0)
    {
        perror("accept error!");
        return -1;
    }

    int n;
    char buf[1024];
    int i;
    while (1)
    {
        memset(buf, 0x00, sizeof(buf));
        n = read(cfd, buf, sizeof(buf));
        if (n

客户端 03-unix-client.c

#include
#include
#include
#include
#include
#include
#include
#include
#include

int main()
{
    // 创建socket
    int cfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (cfd < 0)
    {
        perror("socket create error!");
        return -1;
    }

    // 删除sock文件 文件存在则以为端口还在占用
    unlink("client.sock");

    // 绑定
    struct sockaddr_un client;
    client.sun_family = AF_UNIX;
    strcpy(client.sun_path, "./client.sock");
    int ret = bind(cfd, (struct sockaddr *)&client, sizeof(client));
    if (ret < 0)
    {
        perror("bind error!");
        return -1;
    }

    // 接收新的客户端连接
    struct sockaddr_un serv;
    bzero(&serv, sizeof(serv));
    serv.sun_family = AF_UNIX;
    strcpy(serv.sun_path, "./serv.sock");
    ret = connect(cfd, (struct sockaddr *)&serv, sizeof(serv));
    if (ret < 0)
    {
        perror("connect error");
        return -1;
    }

    int n;
    char buf[1024];
    int i;
    while (1)
    {
        // 读取标准输入
        memset(buf, 0x00, sizeof(buf));
        n = read(STDIN_FILENO, buf, sizeof(buf));
        write(cfd, buf, n);

        memset(buf, 0x00, sizeof(buf));
        n = read(cfd, buf, sizeof(buf));
        if (n

size = offsetof(struct sockaddr_un, sun_path) +strlen(un.sun_path);

define offsetof(type, member) ((int)&((type *)0)->member)

Offsetof 函数用于计算偏移量

//调用offset函数测试结构体成员变量的偏移量
#include
#include
#include

int main(void)
{
    struct s
    {
        int i;
        char c;
        double d;
        char a[1];
    };

    /* Output is compiler dependent */

    printf("offsets: i=%zd; c=%zd; d=%zd a=%zd\n",
            offsetof(struct s, i), offsetof(struct s, c),
            offsetof(struct s, d), offsetof(struct s, a));
    printf("sizeof(struct s)=%zd\n", sizeof(struct s));

    return 0;
}

Linux网络学习 第五天

会进行自动对其 int 4个字节 因此c的偏移量为4

Char 虽然只占一个字节,但自动补齐, 1 + 3 因此d的偏移量为8

A的偏移量为 4 + 4 + 8 =16, 如果char a[1]后面还有,那么偏移量为16 + 8 =24,会自动以最大的2的n次方进行补齐。

Original: https://blog.csdn.net/RYIJU5YUJTY/article/details/128893077
Author: 没有网名L
Title: Linux网络学习 第五天

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/818174/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球