为什么' pthread '没有输出?

why there is no output for `pthread`?

本文关键字:输出 pthread 为什么      更新时间:2023-10-16
#include <pthread.h>
#include <stdio.h>
typedef struct thread_char_para {
    char character;
    int count;
} thread_char_para;
void* char_print (void* parameter)
{
    thread_char_para* p = (thread_char_para*)parameter;
    int i;
    for (i = 0; i < p->count; ++i)
        fputc(p->character, stderr);
    return NULL;
}
int main()
{
    pthread_t thread1;
    pthread_t thread2;
    thread_char_para para1 = {'x', 30000};
    thread_char_para para2 = {'o', 30000};
    pthread_create(&thread1, NULL, char_print, &para1);
    pthread_create(&thread2, NULL, char_print, &para2);
    return 0;
}

为什么没有任何输出?

我也找到了一些链接来阅读:分离与可接合的POSIX线程

在这个链接中,它说pthread_join是不必要的。所以,我想知道。

您需要在pthread_create()之后调用pthread_join()pthread_exit(),否则main()也将返回杀死派生线程。

作为连接两个线程的另一种选择,可以像对待任何其他线程一样对待main() -线程,并使用pthread_exit()退出。

这样做会防止进程和所有的线程在main()返回的那一刻结束。

您应该添加pthread_join调用,以确保您的main函数等待其他线程完成:

int main()
{
    pthread_t thread1;
    pthread_t thread2;
    thread_char_para para1 = {'x', 30000};
    thread_char_para para2 = {'o', 30000};
    pthread_create(&thread1, NULL, char_print, &para1);
    pthread_create(&thread2, NULL, char_print, &para2);
    pthread_join(thread1, NULL);  // <-- add these
    pthread_join(thread2, NULL);  // <--/   two lines.
    return 0;
}

要给您一个关于何时可以避免pthread_join的示例,请查看下面的代码

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
typedef struct thread_char_para {
    char character;
    int count;
} thread_char_para;
void* char_print (void* parameter)
{
    thread_char_para* p = (thread_char_para*)parameter;
    int i;
    if (p->character == 'x')
    {
        pthread_t thread2;
        thread_char_para para2 = {'o', 30000};
        pthread_create(&thread2, NULL, char_print, &para2);
        for (i = 0; i < 5; ++i)
        {
            sleep(1);
        }
    }
    else
    {
        for (i = 0; i < p->count; ++i)
            fputc(p->character, stderr);
    }
    return NULL;
}
int main()
{
    pthread_t thread1;
    thread_char_para para1 = {'x', 30000};
    pthread_create(&thread1, NULL, char_print, &para1);
    pthread_join(thread1, NULL);
    return 0;
}

可以看到,main启动pthread1,等待pthread1完成。pthread1启动另一个thread2并循环5秒,而pthread2正在做它的工作。在这种情况下,不使用pthread_join

main函数返回相当于调用exit。它杀死进程及其所有线程。因此,您的程序在线程有机会运行之前杀死它们。pthread_create并不意味着线程在pthread_create内执行,它意味着线程将在未来的某个时刻执行,创建线程后做的第一件事就是杀死它们,这使得它们很可能还没有机会开始运行。

你可以用不同的方法来解决这个问题。正如其他人提到的那样,您可以等到线程使用pthread_join完成运行,您可以让线程通过管道、信号量、屏障、条件变量和许多其他方式向main指示它们已经完成。你只需要确保main在线程完成之前不能返回,否则你很可能会在它们有机会运行之前杀死它们。

pthread_join是不必要的,因为你提到的答案说。在您的情况下,等待线程完成运行是最简单的方法。严格地说,你甚至不需要等待线程结束运行,你只需要它们向主线程表明它们已经完成了你想让它们做的事情,线程完成是知道它们已经开始运行的最简单的方法。