代码之家  ›  专栏  ›  技术社区  ›  Rob Lourens

从子进程创建pthread

  •  0
  • Rob Lourens  · 技术社区  · 15 年前

    我肯定我遗漏了一些基本的东西,但是我正在编写一个程序,fork()的几个子进程,每个子进程创建几个pthread。似乎pthread_create调用从未从子进程起作用。下面是示例代码来解释我的意思:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    // Listen for a request from user proc i
    void *wait_for_req(void *cvoid) {
         int req;
         int read_ret;
         printf("new thread started\n");
         pthread_exit(NULL);
    }
    
    void spawn_read_threads(int proc_num, int n) {
        int i;
        printf("About to spawn %d read threads\n", n);
        for (i=0; i<n; i++) {
            pthread_t *t;
            printf("spawning new thread\n");
            int create_result = pthread_create(t, NULL, wait_for_req, NULL);
            printf("_create returned %d\n", create_result);
            pthread_join(*t, NULL);
        }
    }
    
    
    int main() {
        if (!fork())
            spawn_read_threads(0, 1);
    }
    

    这个程序的输出是

    About to spawn 1 read threads
    spawning new thread
    

    但是如果我说了如果说了 if (!fork()) :

    About to spawn 1 read threads
    spawning new thread
    _create returned 0
    new thread started
    

    那么为什么在第一种情况下执行不能通过create_result?

    如果这有用:

    rob@ubuntu:/mnt/hgfs/Virtual Machines$ uname -a
    Linux ubuntu 2.6.32-24-generic #42-Ubuntu SMP Fri Aug 20 14:24:04 UTC 2010 i686 GNU/Linux
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   casablanca    15 年前

    我可以看到你的代码有一个直接的问题: pthread_create 地址是 pthread_t 变量并将新线程ID存储在其中。而是传递一个未初始化的指针。你需要做如下事情:

    pthread_t tid;
    int create_result = pthread_create(&tid, NULL, wait_for_req, NULL);
    

    我想说,当它工作一次时,你是幸运的,因为你当前的代码本质上会导致未定义的行为。

        2
  •  1
  •   karunski    15 年前

    除了您在答案中发现的错误之外,您不应该从分叉进程中调用pthread。之后,只应使用fork()异步信号安全函数。必须首先执行exec(),然后才能创建一些pthread。

        3
  •  0
  •   Keshan    15 年前
    pthread_t t;
    printf("spawning new thread\n");
    int create_result = pthread_create(&t, NULL, wait_for_req, NULL);
    printf("_create returned %d\n", create_result);
    pthread_join(t, NULL);
    
    推荐文章