C Printf 不在线程内部打印?

标签 c multithreading pthreads

现在这只是一个小测试,也是学校作业的一部分。在我的代码中,printf 没有打印,至少我无法看到它。这是线程未运行的结果吗?打印线在线程外工作。感谢您的帮助。

我是 c 线程的新手。

#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>


void *threadServer(void *arg)
{
        printf("This is the  file Name: %s\n", arg);
        pthread_exit(0);


}

int main(int argc, char* argv[]){
        int i=1;
        while(argv[i]!=NULL){
                pthread_t thread;
                pthread_create(&thread, NULL, threadServer,argv[i]);
                i++;
        }

最佳答案

在您的代码中,创建另一个线程的执行父线程无需等待其子线程完成即可完成执行。线程与进程不同,一旦父线程终止,其所有执行的子线程也将终止。

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>

void *threadServer(void *arg)
{
    printf("This is the  file Name: %s\n", (char*)arg);
    pthread_exit(0);
}

int main(int argc, char* argv[]){
    int i=1;
    while(argv[i]!=NULL){
        pthread_t thread;
        pthread_create(&thread, NULL, threadServer, argv[i]);
        i++;
        pthread_join(thread, NULL);
    }
}

这样做将允许创建的线程运行,直到它完成执行。 pthread_join 将等待线程完成其执行,然后继续前进。

编辑

正如人们在评论中确实提到的那样,尝试生成一个线程并立即加入它可能毫无值(value),这使得它并不比一个执行线程更好。因此,为了实验方便,代码可以修改如下:

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>

void *threadServer(void *arg)
{
    printf("This is the  file Name: %s\n", (char*)arg);
}

int main(int argc, char* argv[]){
    int i = 1;
    pthread_t thread[argc - 1];

    while(i < argc)
    {
        pthread_create(&thread[i-1], NULL, threadServer, argv[i]);
        i++;
    }

    for (i = 0; i < argc - 1; ++i)
    {
        pthread_join(thread[i], NULL);
    }
}

关于C Printf 不在线程内部打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822000/

相关文章:

c++ - 在 linux 上学习线程

C++ pthread'ed 进程运行速度比单线程问题慢

c - 如何将光标更改为 GTK for C 中的 watch ?

复制部分堆栈并使用 mmap 将其映射到当前进程

c - 矩阵计算器错误 - 无法正常工作

java - 如何在java中单击按钮时暂停线程

c# - 使用线程池复制 100.000 个文件

c - 我的循环在多线程中无法正常运行

c - 如何从特定区域分配内存

c - 用于异步线程的 pthread_join()