2

我正在编写一个 C 程序,一旦它接受客户端连接就会分叉。一旦发生这种情况,我想产生两个线程,但我似乎无法让它工作。

    pthread_t t1, t2;
    void *r_loop();
    void *w_loop();
    .
    .
    .

sockfd = accept(r_sockfd, (struct sockaddr *) &address, &len);
if (sockfd < 0)
    printf("Error accepting\n");

if (!fork())
{
    int r_thread = pthread_create(&t1, NULL, r_loop, NULL);
    int w_thread = pthread_create(&t2, NULL, w_loop, NULL);

    pthread_join(r_thread, NULL);
    pthread_join(w_thread, NULL);
    exit(0);
}

当我运行它时,函数 r_loop 和 w_loop 不会被执行。

4

2 回答 2

5

问题可能是这样的:成功时的 pthread_create() 总是返回零。您正在向 pthread_join() 传递一个不正确的值(即零而不是 t1 和 t2),使它们立即返回。然后下面的 exit() 也会杀死新的启动线程

于 2012-09-11T14:44:31.673 回答
1

你应该通过t1andt2而不是r_threadand w_threadto pthread_join()

于 2012-09-11T14:45:55.120 回答