• Stars
    star
    267
  • Rank 153,621 (Top 4 %)
  • Language
    C
  • License
    MIT License
  • Created almost 8 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Protothreads (coroutines) in C99. Highly portable, but work best in low-end embedded systems.

pt

Build Status

Pt is the most lightweight protothreads or coroutines implementation I could only think of.

Pt allows building subroutines that can suspend at certain points and can be resumed later. These are the building blocks for co-operative multitasking.

Pt has been tested on Linux and bare-metal STM32, but would work just fine on any other embedded platform such as AVR or MSP430.

Features

  • All code is just a single header file - easy to integrate in your project
  • Small code base - only 178 lines of code
  • Simple API - protothread API is only 9 functions
  • Supports switch/case, goto labels or setjmp/longjmp to save coroutine state (continuation)
  • C99 (unless you use goto labels, which is a GCC/Clang extension)
  • Comes with message queues as a bonus (20 lines of code) and a wrapper for POSIX syscalls

Example

typedef pt_queue(struct packet, 32) packet_queue_t;
void producer(struct pt *pt, packet_queue_t *q) {
	pt_begin(pt);
	for (;;) {
		pt_wait(pt, !pt_queue_full(q) && packet_available());
		pt_queue_push(q, packet_read());
	}
	pt_end(pt);
}

void consumer(struct pt *pt, packet_queue_t *q) {
	pt_begin(pt);
	for (;;) {
		/* For for some data in the queue */
		pt_wait(pt, !pt_queue_empty(q));
		struct packet p = pt_queue_pop(q);
		/* process packet here */
	}
	pt_end(pt);
}

...

struct pt pt_producer = pt_init();
struct pt pt_consumer = pt_init();
packet_queue_t queue = pt_queue_init();

for (;;) {
	producer(&pt_producer, &queue);
	consumer(&pt_consumer, &queue);
}

API

Protothread API:

  • struct pt my_pt = pt_init(); - protothread handle.
  • pt_init() - returns an initialize protothread handle.
  • pt_begin(pt) - must be the first line in each protothread.
  • pt_end(pt) - must be the last line in each protothread, changes pt status to PT_STATUS_FINISHED.
  • pt_exit(pt, status) - terminates current protothread pt with the given status.
  • pt_status(pt) - returns pt status. Can be PT_STATUS_FINISHED or PT_STATUS_BLOCKED or any other status passed into pt_exit.
  • pt_yield(pt) - suspends protothread until it's called again.
  • pt_wait(pt, cond) - suspends protothread until cond becomes true.
  • pt_loop(pt, cond) { ... } - executes the loop (yielding on each iteration) while the condition is true, or until break; is called inside the loop.
  • pt_sys(pt, syscall(...)) - suspends protothread while syscall(...) returns -1 and errno says that it should be retried. Should work with most POSIX syscalls.
  • pt_label(pt, status) - low-level API to create continuation, normally should not be used.

Queue API:

  • pt_queue(type, size) - defines queue type of given element type and capacity. Normally should be used as typedef pt_queue(struct my_item, 32) my_item_queue_t;
  • pt_queue_init() - returns initialize queue instance. E.g. my_item_queue_t q = pt_queue_init();
  • pt_queue_len(q) - returns queue length (number of items written and not read).
  • pt_queue_cap(q) - returns maximum queue capacity (size of underlying buffer).
  • pt_queue_empty(q) - returns 1 if queue is empty, 0 otherwise.
  • pt_queue_full(q) - returns 1 if queue is full, 0 otherwise.
  • pt_queue_reset(q) - reset queue to zero length.
  • pt_queue_push(q, item) - pushes item to the queue and returns 1. If queue is full - returns 0.
  • pt_queue_peek(q) - returns pointer to the first item in the queue, or NULL if queue is empty.
  • pt_queue_pop(q) - returns pointer to the first item in the queue moving the read pointer. Returns NULL if queue is empty.

How is it better than other protothread libraries (e.g. Adam Dunkels Protorheads)?

Pt has a very compact implementation of queues, that doesn't require malloc/free, works with any data types and plays nicely with protothreads.

Pt has pt_loop which is much more powerful that pt_wait(), because it can run some non-blocking code while waiting and have nested loops.

Pt support setjmp/longjmp and has a convenient wrapper for syscalls.

Pt doesn't tell you how to schedule protothreads. Since they are just re-entrant functions - you can nest them, call them all in a loop, or build your own scheduler.

Pt is well covered with tests.

License

Code is distributed under MIT license, feel free to use it in your proprietary projects as well.

More Repositories

1

lorca

Build cross-platform modern desktop apps in Go + HTML5
Go
7,954
star
2

jsmn

Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket
C
3,633
star
3

awfice

The world smallest office suite
HTML
3,462
star
4

fenster

The most minimal cross-platform GUI library
C++
513
star
5

tray

Cross-platform, super tiny C99 implementation of a system tray icon with a popup menu.
C
484
star
6

partcl

ParTcl - a micro Tcl implementation
C
467
star
7

metric

Minimal metrics for Go (counter/gauge/histogram). No dependencies. Compatible with expvar. Web UI included.
Go
353
star
8

luash

Tiny lua module to write shell scripts with lua (inspired by Python's sh module)
Lua
302
star
9

o

Tiny and simple React clone
JavaScript
249
star
10

lua-promises

A+ promises in Lua
Lua
216
star
11

log

Ultimately minimal (yet very convenient) logger for Android and Java
Java
157
star
12

tojvm

A toy JVM in Go
Go
156
star
13

webview-python

Python bindings to webview
Objective-C
151
star
14

bfapi

Resilient, scalable Brainf*ck, in the spirit of modern systems design
Go
144
star
15

nokia-composer

Nokia Composer in 512 bytes
HTML
125
star
16

expr

Fast and lightweight math expression evaluator in C99
C
119
star
17

hid

Simple HID driver for Go (pure golang, no dependencies, no cgo)
Go
119
star
18

zs

Absolutely minimal static site generator in Go (powers https://zserge.com)
Go
91
star
19

tinysh

Tiny UNIX shell, de-obfuscated, modernized, and "rewritten in Rust".
C
88
star
20

nanonn

A nano-framework for neural networks
Rust
83
star
21

dotfiles

git clone --bare https://github.com/zserge/dotfiles $HOME/.dotfiles && git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME checkout
Vim Script
79
star
22

lc3-forth

Post-Apocalyptic Computing: bootstrapping Forth environment for LC-3 CPU
C
79
star
23

1bitr

Minimalistic text-based 1-bit music tracker
C
73
star
24

carnatus

A tiny chess engine in Go (sunfish port)
Go
65
star
25

odetoj

Rewrite of Arthur Whitney's one-page J interpreter in Rust
Rust
61
star
26

headline

Ascetic RSS reader in JavaScript, no server required
JavaScript
57
star
27

glob-grep

A little experiment: compare the languages aimed to replace C
Zig
52
star
28

buckbone

A simple android project generator for the Buck build system
Shell
52
star
29

q

Tiny and simple VueJS clone
JavaScript
46
star
30

beep

Cross-platform beep() function
C
43
star
31

slide

An attempt to implement Trikita Slide for desktop
C++
39
star
32

figma-simplify-path

Figma plugin to simplify vector paths
JavaScript
26
star
33

mucks

A tiny terminal session manager for Tmux, Screen and DVTM
Shell
20
star
34

anvil-kotlin-demos

Minimal tutorial/demos for Anvil+Kotlin
Kotlin
18
star
35

zserge.github.io

My static site
HTML
14
star
36

kv

An ultimately minimal persistent key-value store + LRU cache
Go
12
star
37

jsmn.lua

The world fastest JSON parser ported to Lua
Lua
11
star
38

aint

Code for the "AI or AIN'T" blog posts
Go
11
star
39

yu

Yu is a tee-like tool, but with rotation feature like logrotate
C
10
star
40

tab

๐ŸŽผ A tiny CLI tool to render tabs for music instruments (๐ŸŽน๐ŸŽท๐ŸŽบ๐ŸŽธ๐Ÿช•๐Ÿชˆ and many others!)
C
9
star
41

bsoz

One of the most minimal MOS6502 and retro computer emulators!
C
8
star
42

mdns

Very pragmatic mDNS implementation in Go
Go
8
star
43

kveer

A tiny in-memory key-value storage in Go with optional persistence (atomic backup file, or append-only)
Go
7
star
44

bf

Well, everyone has to write a brainf*ck interpreter at some point
C
7
star
45

covered

Trello Cover Card Generator
JavaScript
6
star
46

toy-java-agent

Toy Java agent
Java
6
star
47

atomicwriter

Atomic file writes in Go (using a unique temporary file and atomic rename)
Go
5
star
48

lex

A library for writing lexers in Go
Go
4
star
49

textizer

Minimal android widgets in Scheme
Java
4
star
50

chess

JavaScript
4
star
51

ping

An ultimately minimal social network, messaging, pub/sub and home automation app
4
star
52

tinylangs

Real programming langauges in 50 lines of code
Python
4
star
53

photo

Minimalistic private photo booth
HTML
3
star
54

incr

incr.it backend
JavaScript
3
star
55

zine

Tiny CSS template to produce micro-zines (folded 8-page magazines)
Python
3
star
56

one-click-hugo-cms

CSS
2
star
57

grafana-zero

Python
2
star
58

gif

Simple GIF recorder
HTML
2
star
59

protoc-gen-micro

Protobuf code generation for micro
Go
2
star
60

scaffold

Templates for quick project start
Java
1
star
61

r

Something that rhymes. Or not.
1
star