Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using asynchronous I/O


The D standard library does not include asynchronous I/O functions, but we can still use them by calling C functions or with third-party libraries.

How to do it…

We will execute the following steps to use asynchronous I/O:

  1. Find a C API you like, either the operating system functions or a third-party library such as libuv or libevent, bindings to which can be found at http://code.dlang.org/.

  2. Use the C functions instead of the Phobos functions.

Here's an example of how to get an asynchronous input from a text file on Windows using the Win32 API:

import core.sys.windows.windows; // basic Windows headers
import std.conv;

 // Not all necessary functions are defined in core.sys.windows.windows
 // but that's never a dealbreaker: we can just define the prototypes ourselves
// ReadFileEx is specialized for asynchronous reading
  extern(Windows)
    BOOL ReadFileEx(HANDLE, LPVOID, DWORD, OVERLAPPED*, void*);
// SleepEx will pause the program, allowing our async handler to be called...