[WIP] Threading api (second try)

So this is the second implementation of the threading API after the design changes discussed in #22.

This is a work in progress of course, and I will add features before we can merge it. I just open it to avoid work duplication if someone starts working on it too.