在继续之前,我如何确保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个线程,而不只是一个特定的线程?
发布于 2019-04-01 06:35:28
经过一些实验,这似乎是在内核中模拟基本线程联接的最佳方式。我使用了补全方法,而不是信号量方法,因为我发现它更简单。
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;
}
https://stackoverflow.com/questions/54670652
复制相似问题