Guarantees about threading in `std`


#1

A friend of mine wants to learn Rust by writing a POSIX shell, but he’s decided against it. He needs to be able to fork() so that subshells can share state cleanly (IPC would be too slow; apparently this would not be POSIX compliant, but I’m not a domain expert here). Having some std thing spawn threads, like something that quietly calls a parallel iterator as an implementation detail, makes fork() unsafe. (Note: fork() makes some of the borrowck’s assumptions unsound, but even in C fork() is a hilariouslly unsafe thing you have to take extreme care with).

Fundamentally, I think it would be valuable for std to make guarantees about spawning threads (e.g. any method which may spawn an OS thread is specifically singled out). This is useful in other situations where you must be single-threaded, such as BoringSSL’s lockless mode for embedded. AFAIK, std makes no such guarantees, and "don’t call thread::spawn" is not a complete list of things to do to prevent spawning threads.

Alternatively, a compiler switch to make thread::spawn always panic might be another option, but that seems somewhat hamfisted.


#2

I’m fairly certain nothing in std outside of std::thread spawns threads.


#3

I’m also fairly certain, but that’s not a guarantee. It is not a breaking change for some std API decide to silently spawn threads for parallelizing an algorithm. This is the sort of thing that should be documented, e.g. "std promises that a program not importing any other crates and not calling foreign functions and not calling std::thread will not spawn multiple threads".

When it comes to concurrency, “fairly certain” is never an acceptable answer.


#4

I understand the motivation here but this seems like a weird thing to guarantee. I’m not aware of any other language standard libraries that make similar guarantees. Do C or C++ make this kind of guarantee?

Furthermore, isn’t this exactly what the Send trait is for? Any api that spawns threads will probably place a demand like T: Send on your data.