简体   繁体   English

C Printf不在线程内打印?

[英]C Printf not printing inside of a thread?

Now this is just a little test, and part of a school assignment. 现在这只是一个小测试,也是学校作业的一部分。 In my code printf is not printing at least to me being able to see it. 在我的代码中,printf至少打印不到我能够看到它。 Is this a result of the thread not functioning? 这是线程无法运行的结果吗? The print line works outside of the thread. 打印线在线程外部工作。 Thank you for any help. 感谢您的任何帮助。

I am new to threading in c. 我是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++;
        }

In your code, the parent thread of execution that created another thread finishes execution without waiting for its child threads to finish. 在您的代码中,创建另一个线程的父执行线程在不等待其子线程完成的情况下完成执行。 And threads, unlike processes, once the parent thread terminates, all its child threads of execution terminate as well. 与进程不同,线程一旦父线程终止,其所有子执行线程也会终止。

#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);
    }
}

Doing this will allow the thread created to run, until it finishes execution. 这样做将允许创建的线程运行,直到它完成执行。 The pthread_join will wait for the thread to complete its execution and then move ahead. pthread_join将等待线程完成其执行,然后继续前进。

EDIT 编辑

As people did mention in the comments, it is probably worthless trying to spawn a single thread and joining it immediately, making it no better than a single thread of execution. 正如人们在评论中提到的那样,尝试生成单个线程并立即加入它可能毫无价值,这使得它不比单个执行线程更好。 Hence, for the sake of experimentation, the code can be modified as follows: 因此,为了实验,代码可以修改如下:

#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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM