feat: thread initialization for reverse FFI (#3632)
Makes it possible to properly allocate and free thread-local runtime resources for threads not started by Lean itself
This commit is contained in:
parent
6af7a01af6
commit
3921257ece
3 changed files with 25 additions and 3 deletions
|
|
@ -111,6 +111,15 @@ if (lean_io_result_is_ok(res)) {
|
|||
lean_io_mark_end_initialization();
|
||||
```
|
||||
|
||||
In addition, any other thread not spawned by the Lean runtime itself must be initialized for Lean use by calling
|
||||
```c
|
||||
void lean_initialize_thread();
|
||||
```
|
||||
and should be finalized in order to free all thread-local resources by calling
|
||||
```c
|
||||
void lean_finalize_thread();
|
||||
```
|
||||
|
||||
## `@[extern]` in the Interpreter
|
||||
|
||||
The interpreter can run Lean declarations for which symbols are available in loaded shared libraries, which includes `@[extern]` declarations.
|
||||
|
|
|
|||
|
|
@ -46,18 +46,26 @@ void reset_thread_local() {
|
|||
|
||||
using runnable = std::function<void()>;
|
||||
|
||||
static void thread_main(void * p) {
|
||||
extern "C" LEAN_EXPORT void lean_initialize_thread() {
|
||||
#ifdef LEAN_SMALL_ALLOCATOR
|
||||
init_thread_heap();
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" LEAN_EXPORT void lean_finalize_thread() {
|
||||
run_thread_finalizers();
|
||||
run_post_thread_finalizers();
|
||||
}
|
||||
|
||||
static void thread_main(void * p) {
|
||||
lean_initialize_thread();
|
||||
std::unique_ptr<runnable> f;
|
||||
f.reset(reinterpret_cast<runnable *>(p));
|
||||
|
||||
(*f)();
|
||||
f.reset();
|
||||
|
||||
run_thread_finalizers();
|
||||
run_post_thread_finalizers();
|
||||
lean_finalize_thread();
|
||||
}
|
||||
|
||||
#if defined(LEAN_MULTI_THREAD)
|
||||
|
|
|
|||
|
|
@ -217,9 +217,14 @@ static T & GETTER_NAME() { \
|
|||
}
|
||||
|
||||
namespace lean {
|
||||
// module initializer pair (NOT for initializing individual threads!)
|
||||
void initialize_thread();
|
||||
void finalize_thread();
|
||||
|
||||
// thread initializer pair, for reverse FFI
|
||||
extern "C" LEAN_EXPORT void lean_initialize_thread();
|
||||
extern "C" LEAN_EXPORT void lean_finalize_thread();
|
||||
|
||||
typedef void (*thread_finalizer)(void *); // NOLINT
|
||||
LEAN_EXPORT void register_post_thread_finalizer(thread_finalizer fn, void * p);
|
||||
LEAN_EXPORT void register_thread_finalizer(thread_finalizer fn, void * p);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue