TheMangaStand TheMangaStand - 14 days ago 5
C Question

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

Answer
#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++;
                pthread_join(thread, NULL);
        }

Doing this will allow the thread created to run, until it finishes execution.

In your code, the parent thread of execution that created this 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.