简体   繁体   English

如何在Linux内核中加入多个线程

[英]How to join multiple threads in Linux kernel

How can I make sure multiple threads in the Linux kernel have completed before proceeding? 在继续之前,如何确保Linux内核中的多个线程已经完成?

See the example code (slightly modified) from a previous question ( How to join a thread in Linux kernel? ) 请参阅上一个问题( 如何在Linux内核中加入线程? )的示例代码(略作修改)

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

The answer from this previous question is quite detailed ( https://stackoverflow.com/a/29961182/7431886 ), which is great, but it only addresses the scope of the original question (waiting for only a specific one of the threads to finish). 前一个问题的答案非常详细( https://stackoverflow.com/a/29961182/7431886 ),虽然很好,但是它只解决了原始问题的范围(仅等待特定的线程来完)。

How can I generalize either the semaphore or completion methods detailed in this answer to wait for N threads instead of just a specific one? 如何概括此答案中详述的信号量或完成方法以等待N个线程而不是仅一个特定线程?

After some experimentation, this seems to be the best way to simulate a rudimentary thread join in the kernel. 经过一些试验,这似乎是在内核中模拟基本线程连接的最佳方法。 I used the completion method, not the semaphore method since I found it more straightforward. 我使用完成方法,而不是信号量方法,因为我发现它更简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM