1设计结构
2 设计优点
- 1 充分利用多核系统的并发处理能力
- 2 负载均衡
- 3 职责明确,管理进程仅负责管理,工作进程仅负责处理业务逻辑
3 演示代码:
cpp
//main.cpp
#define _GNU_SOURCE
#include<sys/types.h>
#include<sys/wait.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include<string.h>
#include<errno.h>
//函数指针
typedef void (*spawn_proc_pt) (void* data);
//工作进程
static void worker_process_cycle(void* data);
//启动n个进程
static void start_worker_processes(int n);
//进程分配
pid_t spawn_process(spawn_proc_pt proc, void* data,const char* name);
//设置进程
static void worker_process_init(intptr_t worker);
int main(int argc,char** argv) {
//启动4个进程
start_worker_processes(4);
//进程等待
wait(NULL);
return 0;
}
//设置进程的关系
void worker_process_init(intptr_t worker)
{
//cpu亲源
cpu_set_t cpu_affinity;
//worker = 2; //测试用
//清除cpu掩码
CPU_ZERO(&cpu_affinity);
//设置cpu使用哪个核
CPU_SET(worker % CPU_SETSIZE, &cpu_affinity);// 0 1 2 3 CPU_SETSIZE(cpu最大数量)
//sched_setaffinity
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_affinity) == -1) {//0表示绑定自己进程的pid
fprintf(stderr, "sched_setaffinity() failed,reason:%s\n", strerror(errno));
}
}
void start_worker_processes(int n)
{
int i;
for (i = n - 1; i >= 0; i--)
{
const char *processName= "worker process";
spawn_process(worker_process_cycle, (void*)(intptr_t)i, processName);
}
}
//分配的进程任务
pid_t spawn_process(spawn_proc_pt proc, void* data, const char* name)
{
pid_t pid;
pid = fork();
switch (pid)
{
case -1://创建进程失败
fprintf(stderr, "Create childen process %s failed!, reason:%s .\n", name, strerror(errno));
break;
case 0://创键子进程
proc(data);
break;
default://父进程
break;
}
printf("start %s %d", name, (long int)pid);
return pid;
}
//工作函数
void worker_process_cycle(void* data) {
intptr_t worker = (intptr_t)data;
//初始化进程
worker_process_init(worker);
//开始工作
while(1) {
sleep(10);
printf("pid %ld ,doing ...\n", (long int)getpid());
}
}
4 编译与执行
gcc ./main -o M_Process.exe
./M_Process.exe
5 查看效果
查看系统的核数
cat /proc/cpuinfo
查看分配的进程对应的核
ps -eLo ruser,pid,lwp,psr,args
4个分配的进程分别使用不同的核