What is the difference between a thread and a fiber?

前端 未结 9 906
北荒
北荒 2020-12-07 07:28

What is the difference between a thread and a fiber? I\'ve heard of fibers from ruby and I\'ve read heard they\'re available in other languages, could somebody explain to me

9条回答
  •  隐瞒了意图╮
    2020-12-07 07:41

    Threads use pre-emptive scheduling, whereas fibers use cooperative scheduling.

    With a thread, the control flow could get interrupted at any time, and another thread can take over. With multiple processors, you can have multiple threads all running at the same time (simultaneous multithreading, or SMT). As a result, you have to be very careful about concurrent data access, and protect your data with mutexes, semaphores, condition variables, and so on. It is often very tricky to get right.

    With a fiber, control only switches when you tell it to, typically with a function call named something like yield(). This makes concurrent data access easier, since you don't have to worry about atomicity of data structures or mutexes. As long as you don't yield, there's no danger of being preempted and having another fiber trying to read or modify the data you're working with. As a result, though, if your fiber gets into an infinite loop, no other fiber can run, since you're not yielding.

    You can also mix threads and fibers, which gives rise to the problems faced by both. Not recommended, but it can sometimes be the right thing to do if done carefully.

提交回复
热议问题