C 的 coroutine 库
今天实现了一个 C 用的 coroutine 库.
我相信这个东西已经被无数 C 程序员实现过了, 但是通过 google 找了许多, 或是接口不让我满意, 或是过于重量.
在 Windows 下, 我们可以通过 fiber 来实现 coroutine , 在 posix 下, 有更简单的选择就是 setcontext 。
我的需求是这样的:
首先我需要一个 asymmetric coroutine 。如果你用过 lua 的 coroutine 就明白我指的是什么。
其次,我不希望使用 coroutine 的人太考虑 stack 大小的问题。就是说,用户在 coroutine 内可以使用的 C stack 大小和主线程一样多。
我需要单个 coroutine 空间占有率不要太高,因为我可能会使用上千个 coroutine ,我不希望每个都占用百万字节的堆栈。
因为,在我的应用场合,coroutine 切换的那一刻,使用的堆栈并不多(它可能调用一些需要大量堆栈的库函数,但那些库函数中并不会发生切换),所以,在切换的时刻做栈拷贝是可以接受的。coroutine 切换并不算频繁,这个切换成本是可控的。
最终,我以我的需求实现了我需要的这个版本。
当然,暂时它不支持 windows 。其实 port 到 windows 平台不算困难,只需要把 setcontext 那组 api 改成 fiber 的即可。
Comments
Posted by: helllowhite | (46) April 28, 2020 02:05 PM
Posted by: Cinder | (45) April 26, 2020 08:19 PM
Posted by: vical | (44) December 28, 2017 06:19 PM
Posted by: 余松 | (43) April 5, 2017 03:51 PM
Posted by: progmalover | (42) January 19, 2017 12:12 PM
Posted by: itfanr | (41) December 18, 2016 08:58 PM
Posted by: Anonymous | (40) April 29, 2016 07:28 PM
Posted by: bughoho | (39) September 19, 2015 10:42 PM
Posted by: codechurch | (38) March 3, 2015 01:23 PM
Posted by: xphh | (37) February 25, 2015 09:41 PM
Posted by: xphh | (36) February 25, 2015 09:26 PM
Posted by: Anonymous | (35) December 24, 2014 11:21 AM
Posted by: Anonymous | (34) December 24, 2014 11:17 AM
Posted by: Anonymous | (33) December 24, 2014 11:17 AM
Posted by: Anonymous | (32) December 24, 2014 11:17 AM
Posted by: 啥都不懂就老了 | (31) August 6, 2014 10:18 PM
Posted by: alionkun | (30) March 26, 2014 03:38 PM
Posted by: 浪客 | (29) February 28, 2014 01:23 PM
Posted by: Leo | (28) January 26, 2014 05:44 PM
Posted by: littlewater | (27) October 27, 2013 10:19 AM
Posted by: Cloud | (26) June 18, 2013 12:55 PM
Posted by: plain | (25) June 18, 2013 10:24 AM
Posted by: weager | (24) May 3, 2013 09:26 PM
Posted by: fastfading | (23) November 1, 2012 10:26 AM
Posted by: Alex | (22) October 24, 2012 08:41 AM
Posted by: Genius | (21) August 21, 2012 10:09 AM
Posted by: dannoy | (20) August 20, 2012 11:10 AM
Posted by: Cloud | (19) August 17, 2012 06:16 PM
Posted by: dannoy | (18) August 17, 2012 04:41 PM
Posted by: Genius | (17) August 5, 2012 04:01 PM
Posted by: 古诗词网 | (16) July 27, 2012 12:22 AM
Posted by: 枫叶 | (15) July 26, 2012 11:21 AM
Posted by: David Xu | (14) July 26, 2012 10:31 AM
Posted by: David Xu | (13) July 26, 2012 10:29 AM
Posted by: Cloud | (12) July 25, 2012 08:37 PM
Posted by: David Xu | (11) July 25, 2012 05:26 PM
Posted by: David Xu | (10) July 25, 2012 04:59 PM
Posted by: David Xu | (9) July 25, 2012 04:50 PM
Posted by: Cloud | (8) July 24, 2012 05:55 PM
Posted by: David Xu | (7) July 24, 2012 05:41 PM
Posted by: deverchang | (6) July 24, 2012 01:45 PM
Posted by: changsheng | (5) July 24, 2012 12:29 PM
Posted by: dwing | (4) July 24, 2012 09:50 AM
Posted by: jameslz | (3) July 24, 2012 05:54 AM
Posted by: zr | (2) July 24, 2012 12:40 AM
Posted by: zr | (1) July 24, 2012 12:40 AM