如何强制C程序在特定内核上运行 [英] how to force a c program to run on a particular core

查看:116
本文介绍了如何强制C程序在特定内核上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下c程序:

#include <stdio.h>

int main()
{
    printf("Hello world \n");
    getchar();

    return 0;
}

gcc 1.c -o helloworld

,说我有一台双核计算机:

and, say I have a dual core machine:

cat /proc/cpuinfo | grep processor | wc -l

现在我的问题是,当我们执行程序时,如何强制该程序执行在core-0(或任何其他特定内核)中运行?

Now my question is, when we execute the program, how do we force this program to run in core-0 (or any other particular core)?

如何以编程方式执行此操作?

How to do this programmatically? examples, api's, code reference would be helpful.

如果没有可用的api,那么有编译时间,链接时间,加载时间等方法吗?

If there is no api's available then is there any compile time, link time, load time way of doing this?

OTOH,如何检查程序是否在core-0或core-1(或任何其他内核)中运行?

OTOH, how to check whether a program is running in core-0 or core-1 (or any other core)?

推荐答案

由于您在谈论/ proc / cpu,因此我假设您正在使用linux。在Linux中,您可以使用 sched_setaffinity 函数。在您的示例中,您将调用

Since you are talking about /proc/cpu, I assume you are using linux. In linux you would use the sched_setaffinity function. In your example you would call

cpu_set_t set;
CPU_ZERO(&set);        // clear cpu mask
CPU_SET(0, &set);      // set cpu 0
sched_setaffinity(0, sizeof(cpu_set_t), &set);  // 0 is the calling process

查找 man sched_setaffinity 了解更多详情。

这篇关于如何强制C程序在特定内核上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆