February 25th, 2010

What happens to the fibers which ran on a thread when the thread exits?

What happens to the fibers which ran on a thread when the thread exits? Are all the fibers destroyed? No, only the currently-executing fiber is destroyed. Fibers running on other threads and fibers which are not running on any thread at all are not affected. Fibers do not have thread affinity (when not running), and they do not remember what threads they have been run on. Indeed, one of the features of fibers is that you can switch away from a fiber on one thread, then switch to that same fiber on another thread, and that fiber will resume execution on the new thread. Fibers are the social butterflies of scheduling: They will hang out on any thread that invites them to run. Once one thread deschedules a fiber, the fiber loses any affinity for the thread and is perfectly happy to hang out on any other thread. Or on the original thread, if the original thread comes crawling back begging for another chance. You can run a fiber on any thread you want, provided you don’t run it on two threads at once. (Well, and of course, you have to have prepared the thread for fiber execution by calling ConvertThreadToFiber.)

Next time, some additional musing about fibers.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.