gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:41 28 4
gpt4 key购买 nike

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

最佳答案

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

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

关于c - 如何在 Linux 内核中加入多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com