Thread & FILE descriptor

Hi,
Is a reasonable operation, use as parameters for a thread a file descriptor?
If it is possible, how can i do that?
Thanks in advance
You can pass any parameter you want to a thread. Using pthreads it's something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
myThreadMain(void *p)
{
    // p points to a file descriptor
    int fileDescriptor = *(int*)p;
    // The rest of your code goes here
}

int
main()
{
    int fd = open("somefile", O_RDONLY);
    pthread_t tid;
    pthread_create(&tid, NULL, myThreadMain, &fd);
}
my code is similar to yours...


main
1
2
ifstream f1 (inputfile1);
handles[1]=(HANDLE)_beginthreadex(NULL,0,Run1,&f1,0,NULL);



thread_function

1
2
3
4
5
6
7
8
9
10
11
12
13
static  string  WINAPI Run1(LPVOID lpParam) {
 
   string s;
   ifstream fp = (ifstream)lpParam;
	while (fp.good()){
	
	getline(fp,s);
    cout << s << endl;
	
	
	}
    return s;
}


what could be the problem?
The problem is that you're passing a pointer to ifstream in the call but casting it to an instance of ifstream in the function. You could change Run1 to do this:
 
ifstream *fp = (ifstream*)lpParam;
But then the rest of the code gets a little awkward because you have to dereference the pointer all over the place:
1
2
3
4
while (fp->good()){
    getline(*fp,s);
    cout << s << endl;
}

Instead you could get the pointer and then create a reference:
1
2
3
4
5
6
   ifstream *p = (ifstream*)lpParam;
   ifstream &f(*p);
   while (f.good()) {
	getline(f,s);
        cout << s << endl;
   }
You can even create f directly from lpParam with ifstream &f(*(ifstream*)lParam);

Dave
OK,now it's clear!
Thanks
Topic archived. No new replies allowed.