首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将内核线程绑定到CPU

无法将内核线程绑定到CPU
EN

Stack Overflow用户
提问于 2015-01-02 06:31:25
回答 1查看 2.3K关注 0票数 8

我编写了这段代码来将2个内核线程绑定到不同的CPU:

代码语言:javascript
复制
#include<linux/kthread.h>
#include<linux/sched.h>
#include<linux/delay.h>
#include<linux/slab.h>

struct task_struct *task1;
struct task_struct *task2;
int cpu, data;

int thread_function_one(void *data)
{
    int ret = 10;
    printk(KERN_INFO "IN THREAD FUNCTION 1 \n");

    while(!kthread_should_stop()){
       cpu = get_cpu();
       put_cpu();
       printk("t1 cpu = %d\n",cpu);
       msleep(5000);
    }
    printk(KERN_INFO "EXIT from thread function 1\n");
    return ret;
}

int thread_function_two(void *data)
{
    int ret = 10;
    printk(KERN_INFO "IN THREAD FUNCTION 2 \n");

    while(!kthread_should_stop()){
        cpu = get_cpu();
        put_cpu();
        printk("t2 cpu = %d\n",cpu);
        msleep(6000);
    }
    printk(KERN_INFO "EXIT from thread function 2\n");
    return ret;
}

static int kernel_init(void)
{
   printk(KERN_INFO "module_init\n");

   cpu = get_cpu();
   put_cpu();
   printk("main thread cpu = %d \n",cpu);

   task1 = kthread_create(&thread_function_one,(void *)&data,"one");
   kthread_bind(task1, cpu);
   wake_up_process(task1);

   cpu = 5;
   task2 = kthread_create(&thread_function_two,(void *)&data,"two");
   kthread_bind(task2, cpu);
   wake_up_process(task2);

   return 0;
}

static void kernel_exit(void)
{
   kthread_stop(task1);
   kthread_stop(task2);
   printk(KERN_INFO "module_exit\n");
}

module_init(kernel_init);
module_exit(kernel_exit);
MODULE_AUTHOR("K_K");
MODULE_LICENSE("GPL");

,但是当我在thread_function_one中打印cpu id时,和thread_function_two都打印与主线程相同的CPU。

我是不是弄错了?

本方案的产出:

代码语言:javascript
复制
kernel: [  956.816510] module_init
kernel: [  956.816515] main thread cpu = 8 
kernel: [  956.816743] IN THREAD FUNCTION 1 
kernel: [  956.816748] t1 cpu = 8
kernel: [  956.817057] IN THREAD FUNCTION 2 
kernel: [  956.817062] t2 cpu = 8
kernel: [  961.815160] t1 cpu = 8
kernel: [  962.814649] t2 cpu = 8
kernel: [  966.816760] t1 cpu = 8
kernel: [  968.815711] t2 cpu = 8
kernel: [  971.818307] EXIT from thread function 1
kernel: [  974.816813] EXIT from thread function 2
kernel: [  974.816872] module_exit
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-05 10:44:13

如果"int“变量不是全局变量,则该模块可以正常工作。线程一修改这个全局线程,线程二将自己绑定到同一个CPU。这是主线程、线程一和线程二之间的争用条件。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27738284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档