What are use-cases for a coroutine?

前端 未结 7 1848
你的背包
你的背包 2021-01-30 12:46

The concept of a coroutine sounds very interesting, but I don\'t know, if it makes sense in a real productive environment? What are use-cases for coroutines, that can be solved

7条回答
  •  一整个雨季
    2021-01-30 13:19

    Coroutines can be useful any time a system has two or more pieces of code whose most natural representation would be as a sequential series of steps which involve a lot of waiting.

    For example, consider a device which has an LCD-and-keypad user interface and a modem, and it needs to use the modem to periodically call and report its status independent of what the user at the keypad is doing. The nicest way to write the user interface may be to use functions like "input_numeric_value(&CONV_SPEED_FORMAT, &conveyor_speed);" which will return when a user has entered a value, and the nicest way to handle the communication may be use functions like "wait_for_carrier();" which will return when the unit has either connected or determined it's not going to.

    Without coroutines, either the UI subsystem or the modem subsystem would have to be implemented using a state machine. Using coroutines makes it possible for both subsystems to be written in the most natural style. Note that it's important that neither subsystem ever goes very long without putting things into a "consistent" state and calling yield(), nor calls yield() without putting things into a "consistent" state first, but it's usually not hard to meet those constraints.

    Note that while one could use full-blown multitasking, that requires the use of locks all over the place any time shared state is altered. Since the coroutine switcher won't ever switch things except at yield() calls, either routine can freely alter shared state so long as it ensures that everything in in order before the next yield, and is prepared for the other routine to alter state "during" the yield().

提交回复
热议问题