首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Linux内核中连接多个线程

如何在Linux内核中连接多个线程
EN

Stack Overflow用户
提问于 2019-02-13 20:51:21
回答 1查看 270关注 0票数 1

在继续之前,我如何确保Linux内核中的多个线程已经完成?

参见前面问题(How to join a thread in Linux kernel?)中的示例代码(稍作修改)

代码语言:javascript
复制
void *func(void *arg) {
    // doing something
    return NULL;
}

int init_module(void) {
    struct task_struct* thread[5];
    int i;

    for (i=0; i<5; i++) {
        thread[i] = kthread_run(func, (void*) arg, "TestThread");
        wake_up_process(thread[i]);
    }

    // wait here until all 5 threads are complete

    // do something else

    return 0;
}

上一个问题的答案非常详细(https://stackoverflow.com/a/29961182/7431886),这很好,但它只解决了原始问题的范围(只等待一个特定的线程完成)。

如何将此答案中详细介绍的信号量或完成方法推广为等待N个线程,而不只是一个特定的线程?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-01 06:35:28

经过一些实验,这似乎是在内核中模拟基本线程联接的最佳方式。我使用了补全方法,而不是信号量方法,因为我发现它更简单。

代码语言:javascript
复制
struct my_thread_data {
    struct completion *comp;
    ... // anything else you want to pass through
};

void *foo(void *arg) {
    // doing something
    return NULL;
}

int init_module(void) {
    struct task_struct *threads[5];
    struct completion comps[5];
    struct my_thread_data data[5];

    int i;

    for (i=0; i<5; i++) {
        init_completion(comps + i);
        data[i].comp = comps + i;
        thread[i] = kthread_run(&foo, (void*)(data + i), "ThreadName");
    }

    // wait here until all 5 threads are complete
    for (i=0; i<5; i++) {                                                                             
        wait_for_completion(comps + i);                                                                                                                
    }

    // do something else once threads are complete

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

https://stackoverflow.com/questions/54670652

复制
相关文章

相似问题

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