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

时间:2019-02-13 12:51:21

标签: c linux multithreading linux-kernel

在继续操作之前,如何确保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个线程而不是一个特定的线程?

1 个答案:

答案 0 :(得分:0)

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

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;
}
相关问题