Linux:进程池制作(匿名管道版本 & 定名管道版本) ...

打印 上一主题 下一主题

主题 594|帖子 594|积分 1782

前言

 创建进程是有时间成本的。当计算机要实行任务时才创建进程,势必会影响实行任务的性能。所以我们可以通过提前创建一批进程,当有任务需要被实行时直接喂给这些进程即可。我们把这些提前创建好的进程称为进程池!!
 下面我们会通过一个主进程(父进程)通过匿名管道和一批工作进程(子进程)举行通讯。父进程通过不停派发任务给子进程,子进程通过读取管道文件中的任务码来实行对应的任务,从而模拟进程池的整个行为!!
一、匿名管道制作进程池

一、进程池框架

 父进程创建一批子进程,并创建单向通讯通道。我们这里规定父进程向匿名管道中一次只能写4字节数据,子进程一次只能从管道文件中读取4字节数据。由于匿名管道的性质,父进程只需向目的子进程所对应的管道中发送任务码即可。如果管道文件中存在数据,子进程会不停读取任务码,实行对应的任务;否则子进程进入阻塞状态,等待主进程向管道中写入数据!
 但主进程需要知道向那个管道中发送任务码,向那个匿名管道中举行写入,以及子进程信息。即我们需要对管道举行管理!先描述,在组织!这里我们通过一个类对管道举行描述,其中生存着:主进程控制写端文件描述符、工作进程id和名字!由于我们需要实行快速随机访问,所以选择vector举行组织管理!所以这个进程池的制作大致框架如下:
【描述结构体】:
  1. #define NUM 5//任务进程个数
  2. int number = 1;//管道编号
  3. class channel
  4. {
  5. public:
  6.     channel(int fd, pid_t id)
  7.     :ctrlfd(fd)
  8.     ,workerid(id)
  9.     {
  10.         name = "channle-" + std::to_string(number++);
  11.     }
  12.    
  13. public:
  14.     int ctrlfd;
  15.     pid_t workerid;
  16.     std::string name;
  17. };
复制代码
【框架】:
  1. int main()
  2. {
  3.     std::vector<channel> channels;//用于管理管道
  4.    
  5.     //1、创建管道,创建进程,工作进程工作方式
  6.     CreaterChannel(&channels);
  7.    
  8.     //2、主进程向工作进程发送任务
  9.     // 这里特殊设计,我们通过g_always_loop来判断主进程是一直发送任务,还是发送指定次后就结束退出
  10.     const bool g_always_loop = true;
  11.     SendTask(channels, !g_always_loop, 10);
  12.    
  13.     // 回收资源: 关闭写端,子进程自动退出
  14.     ReleaseChannels(channels);
  15.     return 0;
  16. }
复制代码
二、创建管道、创建进程、工作进程实行任务

2.1 创建管道、创建进程

 我们可以通过父进程循环NUM次,每次先创建管道,然后创建子进程。此时关闭父进程和子进程中不需要的读写段,创建单向通讯通道。此时就可以创建如下关系:

 但上述简单关闭管道文件的读写段会存在题目的!我们需要特殊处理:

 上述这些多余的指向管道读端是fork创建子进程时,子进程继承父进程的信息之一(红线)!所以我们每次创建出的子进程还需将全部继承父进程多余的读端全部关闭,否则无法回收子进程导致内存走漏!!
 其中最简单的解决办法就是:我们将父进程的写端文件描述符全部记录下来,每次创建出子进程时,子进程所继承的多余读写信息已经全部生存。我们只需依次将其关闭即可!!
  1. void CreaterChannel(std::vector<channel> *channels)
  2. {
  3.     std::vector<int> old;//记录子进程继承的多余读端
  4.     for(int i = 0; i < NUM; i++)//创建NUM个工作进程
  5.     {
  6.         // 1. 创建管道
  7.         int pipefd[2];
  8.         int n = pipe(pipefd);
  9.         assert(n == 0);
  10.         (void)n;//防止编译器报警
  11.         //2. 创建子进程
  12.         pid_t id = fork();
  13.         if(id < 0)
  14.         {
  15.             perror("fork");
  16.             return;
  17.         }
  18.         // 3. 形成单向通信
  19.         if(id == 0)//子进程,工作进程
  20.         {
  21.             if(!old.empty())//将子进程继承父进程的多余读端全部关闭
  22.             {
  23.                 for(auto rfd : old)
  24.                 {
  25.                     close(rfd);
  26.                 }
  27.             }
  28.             close(pipefd[1]);
  29.             dup2(pipefd[0], 0);//将读端重定向到标准输入
  30.             work();//子进程执行任务
  31.             exit(0);
  32.         }
  33.         //父进程,主进程
  34.         close(pipefd[0]);
  35.         channels->push_back(channel(pipefd[1], id));//主进程对应写端和工作进程信息
  36.         old.push_back(pipefd[1]);
  37.     }
  38. }
复制代码
2.2 工作进程实行任务

 当管道中有数据时,子进程只需读取相干任务码,然后不停实行即可!但如果此时父进程退出时,由于匿名管道的特性,read的返回值会被设为0,此时子进程在举行读取就没有任何意义了,子进程退出!!(查抄任务码和实行任务码实现后续会同一分析)
  1. void work()
  2. {
  3.     while(1)
  4.     {
  5.         int code = 0;
  6.         ssize_t n = read(0, &code, sizeof(code));
  7.         if(n == 0)
  8.         {//主进程写端退出,子进程也退出
  9.             break;
  10.         }
  11.         else if(n > 0)
  12.         {
  13.             if(!init.CheckSafe(code))//检查任务码是否合法
  14.                 continue;
  15.             init.RunTask(code);//执行任务码
  16.         }
  17.         else
  18.         {
  19.             //nothing
  20.         }
  21.     }
  22. }
复制代码
三、主进程向子进程发送任务

3.1 任务封装

 下面我们仅仅通过一些打印数据来子进程待实行的全部模拟任务
【待实行任务】:
  1. void Download()
  2. {
  3.     std::cout << "我是一个下载任务" << std::endl;
  4. }
  5. void Printflog()
  6. {
  7.     std::cout << "我是一个打印日志任务" << std::endl;
  8. }
  9. void PushVideoStream()
  10. {
  11.     std::cout << "我是一个推送视频流任务" << std::endl;
  12. }
复制代码
【任务封装】:
 我们通过包装器function将上述指针函数举行同一。同时我们向管道中读取和写入的是任务码,所以下面我们给出了相应的任务码,并将上述怎样通过vector容器举行管理,下标对应任务码信息,并封装成了类!
 除此之外,还提供选择任务接口(随机选择)、查抄任务码是否公道、任务码转对应任务名、运行特定任务码对应任务等接口!
 详细如下:
  1. using task_t = std::function<void()>;
  2. class Init
  3. {
  4. public:
  5.     //任务码
  6.     static const int g_Download_code = 0;
  7.     static const int g_Printflog_code = 1;
  8.     static const int g_PushVideoStream_code = 2;
  9.     std::vector<task_t> tasks;
  10. public:
  11.     Init()
  12.     {
  13.         tasks.push_back(Download);
  14.         tasks.push_back(Printflog);
  15.         tasks.push_back(PushVideoStream);
  16.         srand(time(nullptr));
  17.     }
  18.     int SelectTask()//选择任务接口
  19.     {
  20.         return rand() % tasks.size();
  21.     }
  22.     std::string CodeToName(int code)//任务码转对应任务名
  23.     {
  24.         switch(code)
  25.         {
  26.         case 0:
  27.             return "Download";
  28.         case 1:
  29.             return "Printflog";
  30.         case 2:
  31.             return "PushVideoStream";
  32.         default:
  33.             return "Nothing";
  34.         }
  35.     }
  36.     bool CheckSafe(int code)//检查任务码是否合理
  37.     {
  38.         return code >= 0 && code < tasks.size();
  39.     }
  40.     void RunTask(int code)//行特定任务码对应任务
  41.     {
  42.         tasks[code]();
  43.     }
  44. };
  45. Init init;
复制代码
3.2 主进程向子进程发送任务

 思量到子进程完成任务的负载均衡,我们通过循环依次向每一个子进程发送任务码,较为均匀的将任务分配给子进程!
 向子进程发送任务码,起主要确定待发送的任务,信道。然后将任务码写入信道!
 前面已经提到过,我们这里所设计的发送任务接口支持:死循环不停发送任务、发送指定次数任务后退出!所以最后我们需要判定是否发送任务需求竣事,退出!详细如下:
  1. void SendTask(const std::vector<channel> &channels, bool flag, int num)
  2. {
  3.         int pos = 0;//所选择信道所在数组位置下标
  4.     while(true)
  5.     {
  6.         // 1. 选择任务
  7.         int commit = init.SelectTask();
  8.         if(init.CheckSafe(commit))
  9.         {
  10.             // 2. 选择信道, 发送任务码
  11.             channel c = channels[pos++];
  12.             pos %= channels.size();
  13.             write(c.ctrlfd, &commit, sizeof(commit));
  14.         }
  15.         //判断是否需要退出
  16.         if(!flag)
  17.         {
  18.             if(--num == 0)
  19.                 break;
  20.         }
  21.     }
  22. }
复制代码
四、回收资源

 当父进程发送任务信息退出后,我们仅需将写端关闭即可此时子进程实行read的返回值为0。子进程此时就能辨认到写端已经退出,此时子进程也退出!最后让父进程等待子进程,防止子进程僵尸导致内存走漏即可!!
  1. void ReleaseChannels(std::vector<channel> &channels)
  2. {
  3.     for(auto & c : channels)
  4.     {
  5.         close(c.ctrlfd);
  6.         pid_t rid = waitpid(c.workerid, nullptr, 0);
  7.         if(rid == -1)
  8.         {
  9.             perror("waitpid");
  10.             return;
  11.         }
  12.         std::cout << "wait " << c.name << " " << c.workerid << " success" << std::endl;
  13.     }
  14. }
复制代码
五、全部源代码

emsp;到处为止,进程池的简单制作到处就竣事了,下面是全部源码,其中还包含调试代码!
5.1源码

【ProcessPool.chh】
  1. #pragma once #include <iostream>#include <functional>#include <vector>#include <ctime>using task_t = std::function<void()>;void Download()
  2. {
  3.     std::cout << "我是一个下载任务" << std::endl;
  4. }
  5. void Printflog()
  6. {
  7.     std::cout << "我是一个打印日志任务" << std::endl;
  8. }
  9. void PushVideoStream()
  10. {
  11.     std::cout << "我是一个推送视频流任务" << std::endl;
  12. }
  13. class Init{public:    //任务码    static const int g_Download_code = 0;    static const int g_Printflog_code = 1;    static const int g_PushVideoStream_code = 2;    std::vector<task_t> tasks;public:    Init()    {        tasks.push_back(Download);        tasks.push_back(Printflog);        tasks.push_back(PushVideoStream);        srand(time(nullptr));    }    int SelectTask()    {        return rand() % tasks.size();    }    std::string CodeToName(int code)    {        switch(code)        {        case 0:            return "Download";        case 1:            return "Printflog";        case 2:            return "PushVideoStream";        default:            return "Nothing";        }    }    bool CheckSafe(int code)    {        return code >= 0 && code < tasks.size();    }    void RunTask(int code)    {        tasks[code]();    }};Init init;
复制代码
【processPool.cpp】
  1. #include <iostream>#include <unistd.h>#include <cassert>#include <cerrno>#include <cstdlib>#include <string>#include <vector>#include <cstdio> #include <sys/wait.h>#include "ProcessPool.chh"#define NUM 5//任务进程个数
  2. int number = 1;//管道编号
  3. class channel
  4. {
  5. public:
  6.     channel(int fd, pid_t id)
  7.     :ctrlfd(fd)
  8.     ,workerid(id)
  9.     {
  10.         name = "channle-" + std::to_string(number++);
  11.     }
  12.    
  13. public:
  14.     int ctrlfd;
  15.     pid_t workerid;
  16.     std::string name;
  17. };
  18. void work(){    while(1)    {        int code = 0;        ssize_t n = read(0, &code, sizeof(code));        if(n == 0)        {//主进程写端退出,子进程也退出            break;        }        else if(n > 0)        {            if(!init.CheckSafe(code))                continue;            init.RunTask(code);        }        else        {            //nothing        }    }}void CreaterChannel(std::vector<channel> *channels){    std::vector<int> old;//记录主进程的读端    for(int i = 0; i < NUM; i++)    {        // 1. 创建管道        int pipefd[2];        int n = pipe(pipefd);        assert(n == 0);        (void)n;//防止编译器报警        //2. 创建子进程        pid_t id = fork();        if(id < 0)        {            perror("fork");            return;        }        // 3. 形成单向通讯        if(id == 0)//子进程,工作进程        {            if(!old.empty())//将子进程继承父进程多余读端全部关闭            {                for(auto rfd : old)                {                    close(rfd);                }                for(auto id : old)                {                    std::cout << "creater quit id:" << id << " " << std::endl;                }            }            close(pipefd[1]);            dup2(pipefd[0], 0);//将读端重定向到标准输入            work();            exit(0);        }        //父进程,主进程        close(pipefd[0]);        channels->push_back(channel(pipefd[1], id));        old.push_back(pipefd[1]);    }}//Debugvoid PrintChannel(const std::vector<channel> &channels){    std::cout << channels.size() << std::endl;    for(int i = 0; i < channels.size(); i++)    {        std::cout << "name:" << channels[i].name << ", 写端描述符:" << channels[i].ctrlfd                   <<", 工作进程id:" << channels[i].workerid << std::endl;    }    std::cout << "Creater success" << std::endl;}void SendTask(const std::vector<channel> &channels, bool flag, int num){    int pos = 0;//所选择信道地点数组位置下标    while(true)    {        // 1. 选择任务,返回任务码        int commit = init.SelectTask();        if(init.CheckSafe(commit))        {            // 2. 选择信道, 发送任务码            channel c = channels[pos++];            pos %= channels.size();            write(c.ctrlfd, &commit, sizeof(commit));            // Debug            std::cout << "select channel: " << c.name << ", send task:" << init.CodeToName(commit) << "[" << commit << "]"                      << ", workerid:" << c.workerid << std::endl;        }        //判定是否需要退出        if(!flag)        {            if(--num == 0)                break;        }    }}void ReleaseChannels(std::vector<channel> &channels)
  19. {
  20.     for(auto & c : channels)
  21.     {
  22.         close(c.ctrlfd);
  23.         pid_t rid = waitpid(c.workerid, nullptr, 0);
  24.         if(rid == -1)
  25.         {
  26.             perror("waitpid");
  27.             return;
  28.         }
  29.         std::cout << "wait " << c.name << " " << c.workerid << " success" << std::endl;
  30.     }
  31. }
  32. int main(){    std::vector<channel> channels;    //创建管道,创建进程    CreaterChannel(&channels);    std::cout << "Creater end" << std::endl;    PrintChannel(channels);    //主进程向工作进程发送任务    const bool g_always_loop = true;    SendTask(channels, !g_always_loop, 10);        // 回收资源: 关闭写端,子进程主动退出    //sleep(3);    ReleaseChannels(channels);    return 0;}
复制代码
5.2 运行结果(包含调试信息)


六、定名管道实现进程池

6.1 实现思绪

 定名管道实现进程池,我们可以创建多个定名管道,同时父进程打开写端,子进程打开读端!(注意此时创建的子进程还是会出现基础多余的读端文件描述符。所以子进程在打开定名管道读端前,同样需要先将多余的写端描述符关闭)
 发生任务码,和子进程实行任务和匿名管道实现方式一样,就不多说了。
 至于回收资源,那就更简单了。我们只需将定名管道写端描述符关闭,此时子进程会获取的读端退出信息(即read返回值为0),将管道读端也关闭!!最后父进程等待回收子进程,防止子进程僵尸即可!!
6.2 源码

【ProcessPool.cpp】
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <cassert>
  4. #include <cerrno>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <cstdio>
  10. #include <sys/wait.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. #include "ProcessPool.chh"
  15. #define NUM 5//任务进程个数
  16. class fifo
  17. {
  18. public:
  19.     fifo(std::string str, pid_t id, int fd)
  20.     :FILENAME(str.c_str())
  21.     ,workerid(id)
  22.     ,ctrlfd(fd)
  23.     { }
  24.    
  25. public:
  26.     const char *FILENAME;
  27.     pid_t workerid;
  28.     int ctrlfd;
  29. };
  30. int Work()
  31. {
  32.     int code = 0;
  33.     while(true)
  34.     {
  35.         ssize_t n = read(0, &code, sizeof(code));
  36.         std::cout << "read size:" << n << std::endl;
  37.         if(n == 0)
  38.         {
  39.             std::cout << "write quit, mee to!" << std::endl;
  40.             break;
  41.         }
  42.         else if(n > 0)
  43.         {
  44.             init.RunTask(code);
  45.         }
  46.         else
  47.         {
  48.             std::cerr << "errno: " << errno << "errstring: " << strerror(errno) << std::endl;
  49.             return 1;
  50.         }
  51.     }
  52.     return 0;
  53. }
  54. bool Createrfifo(std::vector<fifo> *fifos)
  55. {
  56.     std::vector<int> old;
  57.     for(int i = 1; i <= NUM; i++)
  58.     {
  59.         std::string filename = "fifo-" + std::to_string(i);
  60.         int s = mkfifo(filename.c_str(), 0644);
  61.         if(s == -1)
  62.         {
  63.             std::cout << "errno:" << errno << " strerror" << strerror(errno) << std::endl;
  64.             return false;
  65.         }
  66.         pid_t id = fork();
  67.         if(id == 0)//child
  68.         {
  69.             if(!old.empty())
  70.             {
  71.                 for(auto& fd : old)
  72.                     close(fd);
  73.             }
  74.             int rfd = open(filename.c_str(), O_RDONLY);
  75.             dup2(rfd, 0);
  76.             Work();
  77.             std::cout << "read close!!!!!!!!!!!!!!!!!!!!!" << std::endl;
  78.             close(rfd);
  79.             exit(0);
  80.         }
  81.         //parent
  82.         int wfd = open(filename.c_str(), O_WRONLY);
  83.         fifos->push_back(fifo(filename, id, wfd));
  84.         old.push_back(wfd);
  85.     }
  86.     return true;
  87. }
  88. void SendCommit(const std::vector<fifo> &fifos, int flag, int num)
  89. {
  90.     int pos = 0;
  91.     while(true)
  92.     {
  93.         // 1. 选择任务
  94.         int code = init.SelectTask();
  95.         if(init.CheckSafe(code))
  96.         {
  97.             //2. 发送任务码
  98.             write(fifos[pos].ctrlfd, &code, sizeof(code));
  99.             pos = (pos + 1) % fifos.size();
  100.         }
  101.         // 3.判断是否退出
  102.         if(!flag)
  103.         {
  104.             if(--num == 0)
  105.             {
  106.                 break;
  107.             }
  108.         }
  109.     }
  110.     std::cout << "write finish!!!" << std::endl;
  111. }
  112. void Releasefifo(std::vector<fifo> &fifos)
  113. {
  114.     std::cout << "start release" << std::endl;
  115.     for(auto& fifo : fifos)
  116.     {
  117.         std::cout << "colse wfd: " <<  fifo.ctrlfd << std::endl;
  118.         close(fifo.ctrlfd);
  119.         pid_t id = waitpid(fifo.workerid, nullptr, 0);
  120.     }
  121.     std::cout << "release success!" << std::endl;
  122. }
  123. int main()
  124. {
  125.     std::vector<fifo> fifos;
  126.     // 1.创建命名管道,进程
  127.     if(!Createrfifo(&fifos))
  128.         return 0;
  129.     sleep(2);
  130.     for(const auto& fifo : fifos)
  131.         std::cout << fifo.FILENAME <<":" << fifo.workerid << ":" << fifo.ctrlfd << std::endl;
  132.     // 2.发送任务
  133.     sleep(2);
  134.     bool g_always_loop = true;
  135.     SendCommit(fifos, !g_always_loop, 10);
  136.     // 3. 回收资源
  137.     sleep(2);
  138.     Releasefifo(fifos);
  139.     return 0;
  140. }
复制代码
【ProcessPool.chh】
  1. #pragma once #include <iostream>#include <functional>#include <vector>#include <ctime>using task_t = std::function<void()>;void Download()
  2. {
  3.     std::cout << "我是一个下载任务" << std::endl;
  4. }
  5. void Printflog()
  6. {
  7.     std::cout << "我是一个打印日志任务" << std::endl;
  8. }
  9. void PushVideoStream()
  10. {
  11.     std::cout << "我是一个推送视频流任务" << std::endl;
  12. }
  13. class Init{public:    //任务码    static const int g_Download_code = 0;    static const int g_Printflog_code = 1;    static const int g_PushVideoStream_code = 2;    std::vector<task_t> tasks;public:    Init()    {        tasks.push_back(Download);        tasks.push_back(Printflog);        tasks.push_back(PushVideoStream);        srand(time(nullptr));    }    int SelectTask()    {        return rand() % tasks.size();    }    std::string CodeToName(int code)    {        switch(code)        {        case 0:            return "Download";        case 1:            return "Printflog";        case 2:            return "PushVideoStream";        default:            return "Nothing";        }    }    bool CheckSafe(int code)    {        return code >= 0 && code < tasks.size();    }    void RunTask(int code)    {        tasks[code]();    }};Init init;
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王海鱼

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表