다음을 통해 공유


Fibers

A version of this page is also available for

Windows Embedded CE 6.0 R3

4/8/2010

A fiber is a unit of execution that must be manually scheduled by the application.

Fibers run in the context of the threads that schedule them. Each thread can schedule multiple fibers.

In general, fibers do not provide advantages over a well-designed multithreaded application. However, using fibers can make it easier to port applications that were designed to schedule their own threads.

From a system standpoint, a fiber assumes the identity of the thread that created it. For example, if a fiber accesses thread local storage (TLS), it is accessing the TLS of the thread that created it. In addition, if a fiber calls the ExitThread function, the thread that created it exits.

However, a fiber does not have all the same state information associated with it as that associated with a thread.

The only state information maintained for a fiber is its stack, a subset of its registers, and the fiber data provided during fiber creation. The saved registers are the set of registers typically preserved across a function call.

Fibers are not preemptively scheduled. You schedule a fiber by switching to it from another fiber.

The system still schedules threads to run. When a thread running fibers is preempted, its running fiber is preempted. The fiber runs when its thread runs.

Before scheduling the first fiber, call the ConvertThreadToFiber function to create an area to save fiber state information in. The calling thread becomes the currently executing fiber. The stored state information for this fiber includes the fiber data passed as an argument to ConvertThreadToFiber.

The CreateFiber function is used to create a new fiber from an existing fiber.

The call has the following requirements:

  • The stack size, set to zero.
  • The starting address.
  • The fiber data.

The starting address is typically a user-supplied function, called the fiber function, that takes one parameter, the fiber data, and does not return a value.

If your fiber function returns, the thread running the fiber exits.

To execute any fiber created with CreateFiber, call the SwitchToFiber function.

You can call SwitchToFiber with the address of a fiber created by a different thread. To do this, you must have the address returned to the other thread when it called CreateFiber and you must use proper synchronization.

A fiber can retrieve the fiber data by calling the GetFiberData macro. A fiber can retrieve the fiber address at any time by calling the GetCurrentFiber macro.

To clean up the data associated with a fiber, call the DeleteFiber function.

Take care when calling DeleteFiber: If you call DeleteFiber for a fiber created by another thread, you can cause the other thread to terminate abnormally.

If DeleteFiber is called from the currently running fiber, its thread calls ExitThread.

See Also

Concepts

Processes and Threads

Other Resources

Fiber Reference