【问题标题】:Unable to avoid child processes from inheriting the cpu affinity of parent无法避免子进程继承父进程的 cpu 亲和性
【发布时间】:2014-06-08 18:38:59
【问题描述】:

我想将父进程关联到特定的核心。在下面的代码中,变量 core 是用户提供的参数。之后,我想创建 NUM_CHILDREN 进程,并且每个进程都以循环方式关联到其中一个核心。子进程跳出循环并做更多工作(代码中未显示)。

int child_core = 0;
CPU_ZERO(&mask);
CPU_SET(core,&mask);

if (sched_setaffinity(0, len, &mask) < 0)
{
    perror("sched_setaffinity");
}

for(int i = 0 i < NUM_CHILDREN; i++)
{
    pID = fork();
    if (pID == 0)
    {
        /* child */
        CPU_ZERO(&mask);
        CPU_SET(child_core,&mask);
        len = sizeof(mask);

        if (sched_setaffinity(0, len, &mask) < 0)
        {
            perror("sched_setaffinity");
        }

        break;
    }

    /*parent does some work*/
    child_core = (child_core+1)%6
}

我面临的问题是运行 sar -P ALL 1 100 表明只有一个核心(与父级关联的核心)正在使用。我正在尝试遵循此处提到的解决方案:Cpu affinity inherited by child process

谁能告诉我如何让子进程关联到正确的核心。

【问题讨论】:

    标签: c linux parallel-processing fork affinity


    【解决方案1】:

    我认为您的方法需要让父进程增加计数器 子进程,并且您的亲和代码需要为所有进程执行。

    试试这个:

    /* your call args and return type  may vary, just an illustration */
    void doSetup()
    {
    
        int child_core = 0;
    
        for(int i = 0 i < NUM_CHILDREN; i++)
        {
            pid_t pID = fork();
            if (pID == 0)
            {
            /* child */                 
            break;
            }
            else
            {
             /* parent only */
             child_core = (child_core+1)%6   
            }       
        }
    
    
    
      /* all processes */
    
        cpu_set_t mask;
        CPU_ZERO(&mask);
        CPU_SET(child_core,&mask);
        size_t len = sizeof(mask);
    
        if (sched_setaffinity(0, len, &mask) < 0)
        {
                perror("sched_setaffinity");
        }
        else
        {
          /* child process tasks calls here */
        }
    
        return;
    
    }
    

    this link at IBM DeveloperWorks 有更多示例和讨论

    希望这会有所帮助。

    【讨论】:

    • 我不想移动父进程。我希望它在整个执行过程中绑定到特定的核心。您能否指出我的代码中可能存在的问题?
    • 根据 sched_setaffinity 的手册页,“通过 fork(2) 创建的子代继承了其父代的 CPU 关联掩码。关联掩码在 execve(2) 中保留”我将其解释为意味着在进行子作业时必须将核心作业移到父级上。然后,在分配所有子项后,父项将保留其分配。如果其他用户指出不正确的原因,我会予以纠正。
    • 您能否解释一下 /* 所有进程 */ 将如何执行 sched_setaffinity 调用。子进程立即退出循环,因此它们永远不会到达亲和性。
    • 很好,抱歉。已编辑。
    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 2018-05-22
    • 2017-12-06
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多