简体   繁体   中英

What's the proper usage of Fibers in Windows for C?

I have been recently interested about Fibers in Windows, but I have hard time using it. The documentation involves function definitions and some example, but still some stuff are not clear to me. I see that CreateFiber definition is defined as:

LPVOID CreateFiber(
  SIZE_T                dwStackSize,
  LPFIBER_START_ROUTINE lpStartAddress,
  LPVOID                lpParameter
);

So, we specify the stack size, the function for the fiber and possibly a parameter for the function. Now, my questions are:

1) Once fiber is created, I assume the provided functions execution doesn't immediately start, right? I believe one needs to call ConvertThreadToFiber first. But are there any other stuff needed to be done? I mean in the simplest case, how does defining, initiating, running and deleting a simple fiber looks like?

2) Is it possible somehow to check whether we are actually in the fiber? I mean whether fiber is executing inside some other part of the app? If yes, how?

3) Is it possible to get the memory location of the fiber's stack and the actual content of the fiber's stack at any moment we wish? If yes, how?

(Disclaimer: I've only written a few test programs that use fibers in order to verify that they were working properly while running under a performance profiler that I was working on at the time.)

1) As you say, a fiber does not run by itself. It only runs when another thread explicitly switches to it by calling SwitchToFiber . Execution then continues on that fiber until it calls SwitchToFiber and switches back to the original thread or another fiber.

2) It's unclear to me what you are asking here. If the fiber is the only one calling a particular function it can set some variable or call a function and you'll know it was there. If multiple fibers are calling the same function, maybe they could record their thread id and you'd be able to infer which fiber called the function. What's the use case here?

3) If the fiber is executing, it has access to its stack/registers in the normal way. I am not aware of a way to arbitrarily access the stack of a fiber that isn't currently scheduled to run on a thread, but I suppose you could record the address of the stack from within the fiber itself.

For what it's worth, I don't think the fiber support in Windows API is used much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM