Concurrent Threads and Global Variables

advertisements

I have a function that processes a file. In my main method, I have a loop that creates (# of files) child threads, and processes them concurrently. I have to have a specific output, for example the output needs to be exactly like the files were called, so if my program is called with "a.out file1 file2 file3", the output needs to be "output file1, output file2, output file3".

Right now, it outputs the files in the wrong order, obviously because some threads finish first.

Here is what my code looks like:

char *output[10];

void *file_thread(void *arg)
{
    //processing the file
    // I need to write to output here.
}

int main (int argc, char **argv)
{
    int e;
    int status;
    pthread_t thread[argc - 1];
    // For each file
    for (e = 1; e < argc; e++)
    {
        status = pthread_create(&thread[e-1], NULL, file_thread,
                (char     *)argv[e]);
        if (status != 0)
        {
            err_abort(status, "pthread create");
        }
    }

    for (e=0; e < argc - 1; e++)
    {
        pthread_join(thread[e], NULL);
    }
    /*
    for(e=0; e < argc - 1; e++)
    {
        printf("%s", output[e]);
    }
    */
    return 0;
}

SO what I need to do is in the main method to somehow keep track of the variable e for each thread. I'm not allowed to use pipes. I tried making a different global variable x , assign it to e at each iteration before / after creating a thread, but inside thread_file, it always outputs x to be the value of the final iteration.

Basically, I need the variable e to be stored with different value depending on the file number. Then, at the end of the main method, I can print it in order.

Any help would be much appreciated. Thanks.


The easiest solution would be to make the array of vectors global (make it more dynamic, or foxed at overkill size...) and then let each thread wait for the previous one to finish (thread n calls join on thread n-1, except thread 0) before spitting out its output.

Hopefully they do not start outputting stuff immediately as they start reading their inputs... Or you have to cache it and then wait for the previous to finish before writing that cache.

HTH