【无标题】进程池/Linux

#include <iostream>
#include <vector>
#include <unistd.h>
#include <cassert>
#include <sys/types.h>
#include <string>
#include <sys/wait.h>
// using namespace std;
#include "Tash.hpp"
class channel//封装文件下标fd
{
public:
    channel(int cd, pid_t id) : ctrlfd(cd), workid(id)
    {
    }

public:
    int ctrlfd;
    pid_t workid;
    std::string name;
};
void work()//工作函数
{
    while (true)
    {
        int code = 0;
        ssize_t n = read(0, &code, sizeof code);//取出任务码
        if (n == 4)
        {
            if (!init.Checkcode(code))
            {
                continue;
            }
            init.Runtask(code);//运行
        }
        else if (n == 0)
        {
            break;
        }
        else
        {
        }
    }
    std::cout << "chird quit" << std::endl;
}
void creat(std::vector<channel> *c)
{
    std::vector<int> old;//存储主进程已经打开的pipe文件
    for (size_t i = 0; i < 5; i++)
    {
        int pipefd[2] = {0};//使用匿名管道完成通信
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;
         std::cout<<"creat"<<std::endl;
        int id = fork();
       
        assert(id != -1);
        
        if (id == 0)
        {
            if (!old.empty())//子进程关闭主进程已经打开的pipe文件
            {
                for (const auto fd : old)
                {
                    close(fd);
                }
            }
             close(pipefd[1]);
            dup2(pipefd[0], 0);
            work();
            exit(0);
        }
        close(pipefd[0]);
        c->push_back(channel(pipefd[1], id));
        old.push_back(pipefd[1]);
    }
}
void sendCommand(std::vector<channel> c, int flag, int num=0)
{
    int pos = 0;
    while (true)
    {
        int command = init.SelectTask();
        const auto &tem = c[pos++];
        pos %= c.size();
        std::cout << "send command " << init.Todesc(command) << "[" << command << "]"
                  << " in "
                  << tem.name << " worker is : " << tem.workid << std::endl;
        write(tem.ctrlfd, &command, sizeof command);//将任务写进对应的pipe文件
        if (!flag)//判断是否一直使用
        {
            num--;
            if (num == 0)
                break;
        }
        sleep(1);
    }
    std::cout<<"SendCommand done..." <<std::endl;
}
void Releasechannel(std::vector<channel>c)
{
    for( auto i: c)
    {
        close(i.ctrlfd);
        waitpid(i.workid,nullptr,0);
    }
}
int main()
{
    std::vector<channel> channels;
    creat(&channels);
     const bool g_always_loop = true;
    sendCommand(channels, g_always_loop);
    //sendCommand(channels, !g_always_loop, 10);
    Releasechannel(channels);
    return 0;
}

任务类

#pragma once

#include <iostream>
#include <unistd.h>
#include <functional>
#include <vector>
#include <ctime>
typedef std::function<void()> task;
void Download()
{
    std::cout << "我是一个下载任务"
              << " 处理者: " << getpid() << std::endl;
}

void PrintLog()
{
    std::cout << "我是一个打印日志的任务"
              << " 处理者: " << getpid() << std::endl;
}

void PushVideoStream()
{
    std::cout << "这是一个推送视频流的任务"
              << " 处理者: " << getpid() << std::endl;
}
class Init
{
    public:
        const static int g_download_code=0;
        const static int g_print_log_code=1;
        const static int g_push_video_stream_code=2;
        std::vector<task>tasks;
    public:
        Init()
        {
            tasks.push_back(Download);
            tasks.push_back(PrintLog);
            tasks.push_back(PushVideoStream);
            srand(time(nullptr)^getpid());
        }
        bool Checkcode(int code)
        {
            if(code>=0&&code<tasks.size())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        void Runtask(int code)
        {
            return tasks[code]();
        }
        int SelectTask()
        {
            return rand()%tasks.size();
        }
        std::string Todesc(int code)
        {
            switch (code)
            {
            case g_download_code :
                return "Download";
            case g_print_log_code :
                return "PrintLog";
            case g_push_video_stream_code :
             return "PushVideoStream";
            default:
               return "Unknow";
            }
        }
};
Init init;
  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Linux下使用C语言创建进程,可以按照以下步骤: 1. 创建进程结构体,用于存储进程相关信息,如进程大小、当前已有进程数、互斥锁等。 2. 在主进程中创建进程,即创建一定数量的子进程,将它们放入进程中。 3. 当有任务需要处理时,主进程进程中取出一个空闲进程,将任务分配给它处理。 4. 子进程在处理完任务后,将自己标记为空闲状态,然后等待下一次任务分配。 以下是一个简单的进程实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <pthread.h> #define MAX_PROCESS_NUM 10 #define MAX_TASK_NUM 100 typedef struct { pid_t pid; int is_busy; } Process; typedef struct { pthread_mutex_t lock; Process *process_list; int process_num; int task_num; } ProcessPool; int create_process_pool(int num, ProcessPool *pool); int destroy_process_pool(ProcessPool *pool); int process_task(ProcessPool *pool); int main() { ProcessPool pool; if (create_process_pool(MAX_PROCESS_NUM, &pool) == -1) { printf("Failed to create process pool.\n"); exit(1); } // 处理任务 for (int i = 0; i < MAX_TASK_NUM; i++) { process_task(&pool); } if (destroy_process_pool(&pool) == -1) { printf("Failed to destroy process pool.\n"); exit(1); } return 0; } int create_process_pool(int num, ProcessPool *pool) { pool->process_num = num; pool->process_list = malloc(num * sizeof(Process)); if (pool->process_list == NULL) { return -1; } // 初始化互斥锁 pthread_mutex_init(&pool->lock, NULL); // 创建子进程 for (int i = 0; i < num; i++) { pid_t pid = fork(); if (pid == -1) { return -1; } else if (pid == 0) { // 子进程 while (1) { // 等待任务 pthread_mutex_lock(&pool->lock); for (int j = 0; j < pool->process_num; j++) { if (pool->process_list[j].pid == getpid()) { pool->process_list[j].is_busy = 0; break; } } pool->task_num--; pthread_mutex_unlock(&pool->lock); // 处理任务 printf("Process %d is processing task %d.\n", getpid(), MAX_TASK_NUM - pool->task_num); sleep(1); // 标记为空闲状态 pthread_mutex_lock(&pool->lock); for (int j = 0; j < pool->process_num; j++) { if (pool->process_list[j].pid == getpid()) { pool->process_list[j].is_busy = 0; break; } } pthread_mutex_unlock(&pool->lock); } } else { // 父进程 pool->process_list[i].pid = pid; pool->process_list[i].is_busy = 0; } } // 初始化任务数 pool->task_num = MAX_TASK_NUM; return 0; } int destroy_process_pool(ProcessPool *pool) { // 等待子进程退出 for (int i = 0; i < pool->process_num; i++) { waitpid(pool->process_list[i].pid, NULL, 0); } // 释放资源 free(pool->process_list); pthread_mutex_destroy(&pool->lock); return 0; } int process_task(ProcessPool *pool) { // 找出空闲进程 int index = -1; pthread_mutex_lock(&pool->lock); for (int i = 0; i < pool->process_num; i++) { if (!pool->process_list[i].is_busy) { pool->process_list[i].is_busy = 1; index = i; break; } } pthread_mutex_unlock(&pool->lock); if (index == -1) { // 进程已满,等待空闲进程 sleep(1); process_task(pool); } else { // 分配任务 printf("Task %d is assigned to process %d.\n", MAX_TASK_NUM - pool->task_num, pool->process_list[index].pid); pool->task_num--; } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值