6 ms·
Protothreads: Lightweight Stackless Threads in C
- saagarjha 8y agoThese seem to work with some clever (ab)use of switch statements: http://dunkels.com/adam/pt/expansion.html http://dunkels.com/adam/pt/expansion.html
- greiskul 8y agoWait, how does this work with local variables? Wouldn't the scope be destroyed when you returned, how can it restore the stack if it doesn't save information in the local continuation?
- User23 8y agoThe article mentions Duff's Device. And yes it works.
- webstrand 8y agoIf I understand it correctly, it doesn't. That's why they're called stackless threads. Variables local to the stack frame lose their state, so any internal state needs to be stored in a global.
- saagarjha 8y agoIt doesn't: http://dunkels.com/adam/pt/about.html http://dunkels.com/adam/pt/about.html
- fjfaase 8y agoIndeed, there is a problem with local variables. The example relies on using global variables. If you want multiple threads executing the same function, it is not going to work. Also there is no solution for calling other functions (and have them switch in the middle). A long time ago, I worked on an implementation that does not have these limitations. See: http://www.iwriteiam.nl/Ha_cmt.html http://www.iwriteiam.nl/Ha_cmt.html
- boomlinde 8y ago> The example relies on using global variables. It could as well rely on local variables with static lifetime, though. > If you want multiple threads executing the same function, it is not going to work. That's true for the example, but in general the solution is to pass the protothreads the thread-local state in a struct.
- archgoon 8y ago> > The example relies on using global variables. > It could as well rely on local variables with static lifetime, though. For those following along, static local variables are the same thing as static global variables[1], C just enforces a scoping restriction as to who can access it at compile time. Most compilers will emit the same BSS section entries for both (though they will mangle the symbol name). It's basically compiler syntactic sugar for most compilers (though I'm sure the actual standard itself allows for some weird exotic use cases where they get handled completely differently). [1] Static global variables are symbols that are restricted to a compilation unit (as opposed to regular global variables that can be linked to from another compilation unit). If you run `nm` on them, they'll all have a lower case letter indicating it's type.
- mrpippy 8y agoThat was the original implementation (and still used for non-GNU C). On GCC and Clang though, labels-as-values allows a cleaner implementation: https://github.com/Akagi201/protothreads/blob/master/include/lc-addrlabels.h https://github.com/Akagi201/protothreads/blob/master/include...
- dividuum 8y agoWoo. I wrote the original implementation for that 14 years ago. I discovered local labels when we tried to write some code that used the had multiple yields in the same line. Due to how the switch based implementation worked, this wasn't possible, so I looked for other solutions.
- kitd 8y agoIIRC when Simon Tatham first proposed the mechanism, he suggested it should never be used in production, and whoever does so should be fired!
- baybal2 8y agoAdam is a CEO of Thingsquared =D
- dnlgl 8y agoQuite the opposite, actually. He said that he will probably be fired, but should still insist on it being the right way: "Any coding standard which insists on syntactic clarity at the expense of algorithmic clarity should be rewritten. If your employer fires you for using this trick, tell them that repeatedly as the security staff drag you out of the building." https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
- manwe150 8y agoExcitingly, we soon may be able to have both (if you can compile your C code with a C++ compiler). Coroutines are in the working draft for the C++20 spec, so they may soon be provided by the runtime (and thus integrate into all of the other language features and syntax) instead of requiring hacking it up with string macros: https://en.cppreference.com/w/cpp/language/coroutines https://en.cppreference.com/w/cpp/language/coroutines
- alexhutcheson 8y agoIf you want coroutines before upgrading to a C++20 toolchain, you can also try: - boost::Fiber for C++: https://www.boost.org/doc/libs/1_70_0/libs/fiber/doc/html/index.html https://www.boost.org/doc/libs/1_70_0/libs/fiber/doc/html/in... - boost::coroutine2 for C++: https://www.boost.org/doc/libs/1_70_0/libs/coroutine2/doc/html/index.html https://www.boost.org/doc/libs/1_70_0/libs/coroutine2/doc/ht... (lower level than boost::Fiber, and doesn't include an internal scheduler) - libtask for C: https://swtch.com/libtask/ https://swtch.com/libtask/ In the C++ context, this doc summarizes the distinction between "fibers" and "coroutines", although the terminology is not consistent across language ecosystems: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4024.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n402...
- networkimprov 8y agoRelated: Go-style concurrency for C, http://libmill.org/ http://libmill.org/
- alexhutcheson 8y agoAlthough note that all libmill coroutines are mapped N:1 to OS threads, while goroutines are mapped M:N to OS threads. In other words, libmill won’t let you have run 2+ coroutines simultaneously on different OS cores, but Go will allow that.
- deleted 8y ago[deleted]
- danappelxx 8y agoIn fact, this means that writing concurrent code is easier as you don’t have to worry about synchronizing access to shared state. It also means scaling applications is straightforward, since you are forced to design for horizontal scalability from the get go (similar to deploying node.js). Ive always found it strange that Go has both channels and locks as synchronization primitives.
- signa11 8y agounless you start doing blocking read/write...
- danappelxx 8y agoLibdill IO is nonblocking and calls returns a channel. Reading from the channel yields the coroutine, similar to the await statement in some languages.
- signa11 8y agooh cool ! does that happen for read/write to non-socket fd’s as well ?
- photojosh 8y agoI wrote an entire I2C stack for an 8-bit microcontrolller using this protothread library. I would highly recommend using an RTOS instead. ;)
- sgillen 8y agoany chance that code is up somewhere? Sounds interesting
- baybal2 8y agoMy guess is following: some people will put in doubt the rationale of using threads for embedded development as such. See, MCUs are much more interrupt driven than today's PCs, when it comes to I/O, and don't have to run interface logic as it's usually done in hardware. You can make a widget feel quite snappy and interactive even with very simple linear code. For the few tasks genuinely requiring real parallelism, or programming fancy multicore MCUs, it will likely be that you will need more than just thread separation, and it is better to do it properly than use hacks — in other world, use process separation and let complexities be handled by the OS.
- adrianratnapala 8y agoYou can think of it as the reactor pattern. You only have one physical CPU so all you are doing is churning through callback-based event handlers. The callbacks in this case might be the literal interrupt handlers (in which case your dispatcher "loop" is actually the hardware). Or else you make your interrupt write a little bit of state that then gets dispatched by your actual event loop. Either way, you write responsive software by doing everything in short-running callbacks. I find it amusing that (some) sophisticated GUI and server framework for big computers re-invent this.
- photojosh 8y ago> doing everything in short-running callbacks We call them "interrupt handlers." :)
- carmate383 8y agoCan one completely ditch pthread.h with something like this?
- avodonosov 8y agoHow does it work?
- jlundberg 8y agoThe following page describes the implementation details: http://dunkels.com/adam/pt/expansion.html http://dunkels.com/adam/pt/expansion.html
- huxingyi 8y agoInspired by Protothreads, I implemented a similar framework 5 years ago, well, not exactly a framework, just several lines of macros, which could be used in general purpose not just embedded system (I am not sure if Protothreads can be used in general purpose). I used it in product environment with libuv, here is the github link: https://github.com/huxingyi/c-block https://github.com/huxingyi/c-block
- MrBuddyCasino 8y agoIf "running multiple tasks on an embedded system that share a stack" sounds interesting to you, Rust's RTFM is actually quite clever[0]. It only works on ARM MCUs right now, but tasks are IRQ triggered, have a priority, memory safe, deadlock-free and have very low overhead. Scheduling is done in hardware via the interrupt controller. [0] https://github.com/japaric/cortex-m-rtfm https://github.com/japaric/cortex-m-rtfm
- srfilipek 8y agoI hate protothreads with a passion. Not because of what they do (it's a neat trick), but because it teaches bad development practices to programmers. I had a junior programmer "correct" me on some embedded code saying that all my local variables should actually be declared static, because in their experience "static is the way to go". This "embedded" system was actually running Linux, using proper threading semantics.
- marssaxman 8y agoThat's a matter of using the right tool for the environment, though, isn't it? Someone looking at the world from the small-system, bare-metal embedded development perspective might express similar feelings about garbage collection, for teaching junior programmers to be unacceptably sloppy about memory management. I think it is simply to be expected that junior programmers will frequently pick the wrong tool for the job, for any job in any context, as they have not yet had time to master many tools and do not yet have enough experience to understand the edges of their ignorance. (Presumably we would start thinking of them as peers and calling them "senior programmers" at some point along this journey of growth...)