Ai
1 Star 0 Fork 0

加法器+/Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ProcessPool.cc 3.18 KB
一键复制 编辑 原始数据 按行查看 历史
加法器+ 提交于 2024-01-03 15:34 +08:00 . 进程池
#include"Task.hpp"
#include<string>
#include<vector>
#include<cassert>
#include<ctime>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
const int processNum = 10; //一次性创建5个子进程
std::vector<task_t> tasks;
class channel
{
public:
channel(int cmdFd, pid_t slaverId, const std::string &processName)
:_cmdFd(cmdFd)
,_slaverId(slaverId)
,_processName(processName)
{}
public:
int _cmdFd; //发送任务的文件名描述符
pid_t _slaverId; //子进程pid
std::string _processName; //子进程名字
};
void Slaver()
{
int cnt = 2;
while(true)
{
int cmdCode = 0;
int n = read(0, &cmdCode, sizeof(cmdCode));
if(n == sizeof(int))
{
std::cout << "slaver say@get a command:" << getpid() << " : cmdCode: " << cmdCode << std::endl;
if(cmdCode >= 0 && cmdCode < tasks.size()) tasks[cmdCode]();
}
if(n == 0) break;
}
}
void InitProcessPool(std::vector<channel> *channels)
{
std::vector<int> oldfds;
for(int i = 0; i < processNum; i++)
{
int pipefd[2] = {0};
//管道创建
int n = pipe(pipefd);
assert(!n);
(void)n;
pid_t id = fork();
if(id == 0)
{
//关闭上一个写端
for(auto e : oldfds) close(e);
//child 读端
close(pipefd[1]);
dup2(pipefd[0],0); //重定向,从管道里读
close(pipefd[0]);
Slaver();
exit(0);
}
//father 写端
close(pipefd[0]);
std::string name = "process -" + std::to_string(i);
//匿名对象
channels->push_back(channel(pipefd[1], id, name));
oldfds.push_back(pipefd[1]);
}
}
void Debug(const std::vector<channel> &channels)
{
for(const auto &e : channels)
{
std::cout << e._cmdFd << " " << e._processName.c_str() << " " << e._slaverId << std::endl;
}
}
void CtrlProcess(const std::vector<channel> &channels)
{
int cnt = 5;
while(cnt--)
{
//随机发布任务
int cmdCode = rand()%tasks.size();
//选择进程
int processPos = rand()%sizeof(channels.size());
std::cout << "father say@" << "command:" << cmdCode << " already sendto " << channels[processPos]._slaverId << " process name:"
<< channels[processPos]._cmdFd << std::endl;
//发送任务
write(channels[processPos]._cmdFd, &cmdCode, sizeof(cmdCode));
sleep(1);
}
}
void QuitProcess(const std::vector<channel> &channels)
{
//关闭文件描述符
for(const auto &e : channels)
{
close(e._cmdFd);
std::cout << e._cmdFd << " " << e._processName << " " << e._slaverId << std::endl;
sleep(1);
waitpid(e._slaverId, nullptr, 0);
}
}
int main()
{
LoadTask(&tasks);
srand(time(nullptr)^getpid()^1023);
//进程组织
std::vector<channel> channels;
//初始化--创建子进程、建立通信信道
InitProcessPool(&channels);
Debug(channels);
//控制子进程
CtrlProcess(channels);
//sleep(1000);
//清理收尾
QuitProcess(channels);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/PYH_2001/linux.git
git@gitee.com:PYH_2001/linux.git
PYH_2001
linux
Linux
master

搜索帮助