Fibers

Lionello Lunesu lionello at lunesu.remove.com
Wed Oct 22 23:54:55 PDT 2008


"dsimcha" <dsimcha at yahoo.com> wrote in message 
news:gdm4ek$1qmh$1 at digitalmars.com...
>I noticed that, in D 2.20, we now have an implementation of fibers for D2. 
>I
> understand the basic differences between a fiber and a thread (preemptive 
> vs.
> cooperative multitasking, threads can take advantage of multicore, fibers
> can't).  However, from a more practical point of view, I've become 
> curious,
> what are fibers actually good for?  What can be done with fibers that 
> either
> can't be done at all or can't be done as efficiently/elegantly/safely with
> threads?

I've used fibers for the following:

I had to add compression support to some old file-IO API. The basic call I 
had to implement was void read(void*,size_t). The compression API I was 
using had a callback void process_data(void*, size_t). I used fibers to 
switch back and forth between the decompression and the reading. This 
prevented any memory allocation and saved an additional memcpy.

This could also have been implemented using thread, but not without major 
synchronization.

LPVOID io_fiber, comp_fiber;
void* unpacked_data;
size_t unpacked_size, unpacked_pos;

//decompression callback
static void process_data(void* data, size_t size)
{
  unpacked_data = data;
  unpacked_size = size;
  unpacked_pos = 0;
  SwitchToFiber(io_fiber);
  // when we return we need more data
}

//IO api
void read(void* data, size_t size)
{
  while (true)
  {
      int data_available = unpacked_size - unpacked_pos;
      if (data_available)
      {
         int copy = min(data_available, size)
         memcpy(data, unpacked_data+unpacked_pos, copy );
         unpacked_pos += copy;
         data += copy;
         size -= copy;
      }
      if (size == 0)
         break;
      SwitchToFiber(comp_fiber);
      // when we return we have new data
  }
}




More information about the Digitalmars-d mailing list