Matt
Matt

Reputation: 482

Threading with files

#include<pthread.h>
    #include<iostream>
    #include<fstream>
    #include<sstream>
    #include<vector>
    #include<algorithm>

    using namespace std;
    pthread_t threads[10];
    pthread_mutex_t mut;

    void *print(void *fname){
            char *filename=(char*)fname;
            ifstream file;
            vector<string> lines;
            file.open("argi.txt");
            pthread_mutex_lock(&mut);

            while(file.is_open()){
                    string line;
                    while(getline(file,line)){
                            lines.push_back(line);
                    }
            file.close();
            }
            int i;

                for(i=lines.size()-1;i>=0;i--)            
                cout<<lines[i]<<endl;

            pthread_mutex_unlock(&mut);
            pthread_exit(NULL);
            return NULL;
    }


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

            pthread_mutex_init(&mut,NULL);
            for(int i=1;i<argc;i++){

                    pthread_create(&threads[i],NULL,print,(void*)argv[i]);
            }
            for(int i=1;i<argc;i++)
                    pthread_join(threads[i],NULL);
            pthread_mutex_destroy(&mut);

            return 0;}

Now this is supposed to take n file names,for each file a thread will be created and will display the lines of the file in reverse order. ./a.out arg1.txt arg2.txt is the command I'm using and what I get is a screen of unreadble characters.The 2 files exist and each have 5 lines of text.What's wrong with this and how can be fixed?

Upvotes: 0

Views: 57

Answers (2)

user4815162342
user4815162342

Reputation: 154876

Your print function is opening "argi.txt" instead of filename, the file name received from the caller. With this correction, your program works for me.

Additional remarks:

  • You should remove the mutex around the whole function, as it is effectively serializing your threads. Without the possibility of parallel execution, the whole point of using threads is missed.

  • The call to pthread_exit() right before the thread function returns anyway is unnecessary and can be removed.

  • Global pthread mutexes can be initialized with the PTHREAD_MUTEX_INITIALIZER macro, in which case they don't require a call to pthread_mutex_init and pthread_mutex_destroy.

Upvotes: 3

john
john

Reputation: 87959

Obviously file.open("argi.txt"); is incorrect, you have no file called "argi.txt". Presumably you meant file.open(filename);

while(file.is_open()) is a bit odd too, if (file.is_open()) is more natural.

Not sure about the screen of unreadable text however. Presumably there are other issues.

Upvotes: 2

Related Questions