简体   繁体   中英

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. 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.

#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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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