jart / cosmopolitan

build-once run-anywhere c library
ISC License
17.71k stars 605 forks source link

Design consideration for implementing pthread #277

Open lemaitre opened 2 years ago

lemaitre commented 2 years ago

I am planning to implement the pthread interface for cosmopolitan.

I think I can make it work with a small memory footprint by having most functions using a portable implementation (centered around atomics). The few operations that could not be portable are basically: thread_create, atomic_wait (futex) and maybe thread_detach and tls_init. All the other operations could be (in theory) implemented with portable atomics on top of those.

I already did a POC outside cosmopolitan and thanks to the clone syscall, the creation of a thread on Linux is ~30 instructions.

So now I have a few questions:

lemaitre commented 2 years ago

Here are my own answers to those questions:

Do we need to support TLS of dynamic modules? (loaded with dlopen)

I would say yes, but I would prefer no.

Where should go .tdata and .tbss sections?

Just after .data?

Is there any interest in having pthread cancellation points?

I'm not sure to see what is the use of cancellation points. Maybe we could just kill the thread?

Should we add signal masks and CPU affinities?

I don't think it is necessary at the beginning.

Do we want fair locks?

I personally don't. I think most of the time, a fast lock is better than a fair lock. And fast locks are much simpler to implement than fair ones.

Do we want thread stack cache?

I would say no: if you have a program that would benefit from such a cache, you are probably even better to just reuse your threads instead of creating/deleting them all the time.

Do we want a multithreaded malloc being a part of this interface?

I would say yes, but I would appreciate some help on that. So maybe not for a start.

pkulchenko commented 2 years ago

Do we need to support TLS of dynamic modules? (loaded with dlopen) I would say yes, but I would prefer no.

There is no current dlopen support in cosmopolitan, so I'd say we can cross that bridge when we get there.