ryandonohue
ryandonohue

Reputation: 189

Thread not hitting thread function every time

I am trying to make a program that takes several files, appends them all into one big file. Each append has to be done by a separate thread.

/*
This program creates appends several files together
*/

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


pthread_t *tids;

void *threadout(void *num);


int main(int argc, char *argv[])
{

    int numOfFiles = atoi(argv[2]);
    int error;
    int index;

    sem_t sem;

    //Used for output file
    int outFile;

    //Checking to make sure there is the correct number of arguments
    if (argc != 4)
    {
        printf("%s \n", "Wrong number of arguments, exiting program.");
        return 1;
    }

    //checking to make sure there are at least two files to append
    if (numOfFiles < 2)
    {
        printf("%s \n", "Cannot append 1 file or less.");
        return 1;
    }

    //opening/creating file
    outFile = open(argv[3], O_WRONLY | O_CREAT, S_IRUSR);

    ///****************** Allocate space for thread ids ******************/

    tids = (pthread_t *)calloc(numOfFiles, sizeof(pthread_t));
    if (tids == NULL)
    {
        perror("Failed to allocate memory for thread IDs");
        return 1;
    }
    if (sem_init(&sem, 0, 1) == -1)
    {
        perror("Failed to initialize semaphore");
        return 1;
    }

    /****************** Create threads *********************************/

    for (index = 0; index < numOfFiles; index++)
    {
        if (error = pthread_create(tids + index, NULL, threadout, &index))
        {
            fprintf(stderr, "Failed to create thread:%s\n", strerror(error));
            return 1;
        }
    }

    return 0;
}

void * threadout(void *num)
{
    printf("Hello");
    return NULL;
}

Near the bottom of the program I do the actual creating of the threads. The first thing the thread should do is hit the "threadout" function. However the only way I can get anything to print is if I say to create a large number of threads. So if I tell my program to create 5000 threads, "Hello" will be printed. Not 5000 times though. If I asked it to create 10 threads nothing is printed. Am I doing something wrong when I invoke "threadout"? Thanks

Upvotes: 0

Views: 32

Answers (1)

Returning from main causes your entire program to exit, even if other threads are running.

Your main function exits when all threads are started. If you're starting lots of threads, this leaves enough time for the first ones to print. If you're starting few threads, it returns before the first ones get to print anything.

You might want to use pthread_join (called once per thread) to wait for all threads to terminate.

Upvotes: 2

Related Questions