How can I make sure multiple threads in the Linux kernel have completed before proceeding?
See the example code (slightly modified) from a previous question ( 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;
}
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).
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?
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.