【问题标题】:creating pthreads after a fork在 fork 之后创建 pthread
【发布时间】:2012-09-11 14:33:13
【问题描述】:

我正在编写一个 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 不会被执行。

【问题讨论】:

  • 函数需要声明为void * (void *)。
  • 提示:始终测试 API 调用的返回值是否有错误。错误代码是你的朋友。

标签: c sockets pthreads fork


【解决方案1】:

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

【讨论】:

  • 你在使用 Linux/glibc 吗?关于他们的 pthread 实现的一件令人沮丧的事情是 pthread_t 被定义为 long(尽管它实际上存储了一个指针),这意味着编译器无法捕获这样的错误。如果 pthread_t 被定义为 struct __pthread_struct * 或类似的,编译器会抛出一个非常有用的错误消息。
【解决方案2】:

您应该将t1 和t2 而不是r_thread 和w_thread 传递给pthread_join()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2018-03-08
    • 1970-01-01
    相关资源
    最近更新 更多