c - 第二个分离线程不打印消息

标签 c multithreading

尝试建立一个小型的客户端-服务器程序。但是,我注意到第二个线程的输出没有打印出来。

void *ClientRoutine(void *args){
    printf("Client thread created\n");

    pthread_exit(NULL);
}

int main(int argc, char *argv[]){
    pthread_t client_thread;
    pthread_attr_t attr;

     pthread_attr_init(&attr);
     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    if (pthread_create(&client_thread, &attr, &ClientRoutine, NULL)) {
        perror("Failed to create client thread");
        exit(-1);
    }

    pthread_attr_destroy(&attr);

    return 0;
}

如果我在主线程中 printf 某些内容,客户端的输出最终会显示出来。谁能解释一下为什么会发生这种情况?

LE:正如你们中的一些人所建议的,这种情况确实会发生,因为主线程提前退出。然而,根据这个:What happens to a detached thread when main() exits? ,即使 main 退出后,分离的线程也应该继续执行。为什么会出现这种情况?

最佳答案

也许您过早地销毁了分离的线程?如果您只是创建线程然后销毁它,那么您甚至不给 printf 执行时间。尝试在 main 中创建线程后添加一些 sleep 时间,您将看到输出。

当您在主线程中添加另一个 printf 时,您会在另一个线程被销毁之前给其执行时间。

关于c - 第二个分离线程不打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794082/

相关文章:

Node.js 异步调用处理和多核扩展

c - 重用纹理 SDL

c - 使用 C UDP 套接字的选择性重复 ARQ

c - 标准输出上的数据显示错误 : C File Operation

java - Kafka 消费者卡在 iterator.hasNext() 处(实际上是暂停和恢复),即使主题中有大量消息可供使用

c++ - 使用 4 和 8 线程运行的相同时间执行

从 Swift 调用 Rust

c - 从大型 C 数组中的函数访问元素时出错

multithreading - TMultiReadExclusiveWriteSynchronizer死锁

c - 向线程发送消息是什么意思?