代码之家  ›  专栏  ›  技术社区  ›  Mike R

如何在linux内核中连接多个线程

  •  0
  • Mike R  · 技术社区  · 7 年前

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

    0 回复  |  直到 7 年前
        1
  •  0
  •   Mike R    7 年前

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

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