无法避免子进程继承父级的cpu亲和性

时间:2014-06-08 18:38:59

标签: c linux parallel-processing fork affinity

我想将父进程与特定核心联系起来。在下面的代码中,变量 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

有人可以告诉我如何让子进程与正确的核心相关联。

1 个答案:

答案 0 :(得分: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

还有更多示例和讨论

希望这有帮助。