Asynchronous file read

Aug 24, 2009 at 3:16am
Hello all,
How can I open a file in asynchronous mode in a console application? I would like to open both ASCII and BINARY files, but first an ASCII file. Thank you for your time.

Last edited on Aug 24, 2009 at 3:18am
Aug 24, 2009 at 5:31am
I only know the answer for Windows, but since you did not ask in the Windows Programming forum, I am not sure if my answer will be good for you. Drop a line if I should post.
Aug 24, 2009 at 12:26pm
Hi webJose,
Yes my question was for Windows environment only. Kindly post your reply. Thank you.
Aug 24, 2009 at 3:33pm
You can either use the ReadFile() or ReadFileEx() functions. You need to provide an OVERLAPPED structure. The structure will provide the function call with a callback function that will be called once the file read is complete.

The catch: In order for the callback function to be called, the calling thread (the one that called ReadFile() or ReadFileEx()) has to be in an alertable state. You can read more about the alertable state and Asynchonous Procedure Call if you read the MSDN library help topic for the function QueueUserAPC() (http://msdn.microsoft.com/en-us/library/ms684954%28VS.85%29.aspx).

Basically, you use one of the extended wait functions enumerated in that webpage to suspend the thread and wait for the read function call to call the callback function.

That would be the single-threaded asynchonous approach.

As usual, you can also spawn a new thread and call ReadFie() from that second thread and make the call synchronous. The new thread will be blocked, but the main thread will be free. All you have to do afterwards is synchronize both threads using a synchronization object, such as an event. Personally, I would go for this one for a console application. I would only consider the APC solution for a windows GUI application where you use MsgWaitForMultipleObjectsEx() in the main message pump as opposed to the usual GetMessage() function call.
Aug 25, 2009 at 11:05am
Hello webJose
Thank you very much for your post. It is indeed clear and I will go through the link to learn more. I am not an experienced programmer and I have never used threads so far, though I am eagerly looking forward to using threads.

Regards
Topic archived. No new replies allowed.