Streams in C++

General OpenMP discussion

Streams in C++

Postby hywc » Fri Jun 20, 2008 8:14 am

So I'd like to parallelise some code, written in C++, where a different file is opened (and read from) on each iteration of a for loop.

In C++, I can't access copy constructors for ifstreams, so how can I ensure there is an initialised ifstream on each parallel thread?

Code: Select all
   
ifstream reader;
string path;
#pragma omp parallel for private(path) private(reader)
   for (int u=0; u<uMax; u++)
   {
       path = getPath(u);
       reader.open(&path[0], ios_base::in);
      //STUFF
       reader.close();
   }


Sorry if this is a really obvious question, thanks for any help.
HC
hywc
 

Re: Streams in C++

Postby kintaro » Fri Jun 20, 2008 8:32 am

Hi,

I'm a newbie for the openMP and I would like to know the answer to this post too!

Cheers

Kintaro
kintaro
 
Posts: 7
Joined: Wed Jun 18, 2008 5:16 am

Re: Streams in C++

Postby ankit_mait_07 » Fri Jun 20, 2008 10:05 pm

Hi..
Even i have been looking for the answer to this post... After reading a couple of tutorials it seemed tht this was not possible...Maybe i misunderstood....

Regards
Ankit
ankit_mait_07
 
Posts: 14
Joined: Wed Jun 18, 2008 11:20 am

Re: Streams in C++

Postby kintaro » Sat Jun 21, 2008 6:14 am

I think that you could try some array of strings (that will contain the paths) , and using the thread number to access to the element that you need.

Example: (just to provide you an idea)

Code: Select all
   
       char *vPaths={"mypathname1", "mypathname2"};
       
       // ...so 2 threads will start....
       omp_set_num_threads(2);

       #pragma omp parallel private(nthreads, tid)
   {
     /* Obtain thread number */
     tid = omp_get_thread_num();
     printf("Opening file = %s\n", vPaths[tid]);

     if (tid == 0)
     {
       nthreads = omp_get_num_threads();
       printf("Number of threads = %d\n", nthreads);
     }
  }


Cheers

Kintaro
kintaro
 
Posts: 7
Joined: Wed Jun 18, 2008 5:16 am

Re: Streams in C++

Postby ejd » Wed Aug 13, 2008 11:26 pm

I have to say that I would feel better it this question were about C. However, the following seems to work to output data to different files using streams, so I am not sure why you can't get input from different files as well.

Code: Select all
#include <omp.h>
#include <fstream.h>
using namespace std;

int main(void)
{       
  char *vPaths[2] = {"file1", "file2"};
  ofstream writer;
           
  omp_set_dynamic(0);
  omp_set_num_threads(2);

  #pragma omp parallel private(writer)
  {
    #pragma omp for
    for (int i = 0; i < 2; i++)
    {
       writer.open(vPaths[i], ios_base::out);
       writer << "written from thread no: " << omp_get_thread_num() << endl;
       writer.close();
    }
  }
  return 0;
}


Last bumped by Anonymous on Wed Aug 13, 2008 11:26 pm.
ejd
 
Posts: 1025
Joined: Wed Jan 16, 2008 7:21 am


Return to Using OpenMP

Who is online

Users browsing this forum: No registered users and 11 guests