【问题标题】:How to join multiple threads in Linux kernel如何在 Linux 内核中加入多个线程
【发布时间】:2019-02-13 12:51:21
【问题描述】:

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

查看上一个问题 (How to join a thread in Linux kernel?) 中的示例代码(稍作修改)

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 个线程而不仅仅是一个特定的线程?

【问题讨论】:

  • 只需等待每个线程的完成,一个接一个。当您在for 循环中运行线程时,您还可以使用for 循环等待每个线程完成。
  • 我不希望线程按顺序运行。线程应该并行运行。
  • 顺序等待线程完成绝不是顺序运行线程。线程仍然可以并行运行,并且可以按任意顺序完成。

标签: c linux multithreading linux-kernel


【解决方案1】:

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

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2020-12-14
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2016-02-05
    相关资源
    最近更新 更多