Multithreading ============== There are some utilities for using AngelScript in the multithreading environment. .. note:: AngelScript does not support multithreading on all platforms. .. doxygenfunction:: asbind20::has_threads Initializing and Cleaning the Multithreading Environment -------------------------------------------------------- `According to the official document `_, AngelScript needs some additional efforts to work in the multithreading environment. The following functions are provided by the external header ``concurrent/threading.hpp``. .. doxygenfunction:: asbind20::concurrent::auto_thread_cleanup .. doxygenfunction:: asbind20::concurrent::prepare_multithread Example code: .. code-block:: c++ #include #include #include int main() { if(!asbind20::has_threads()) { std::cerr << "AS_NO_THREADS" << std::endl; return 1; } using namespace asbind20; concurrent::prepare_multithread(); auto engine = make_script_engine(); auto* m = engine->GetModule( "script_multithreading", asGM_ALWAYS_CREATE ); m->AddScriptSection( "script_multithreading", "int fn(int arg) { return arg * 2; }" ); m->Build(); auto* f = m->GetFunctionByName("fn"); std::condition_variable cv; std::mutex mx; int result = -1; auto helper = [&, f](int arg) { concurrent::auto_thread_cleanup(); { using namespace std::chrono_literals; request_context ctx(engine); std::this_thread::sleep_for(3ms); // Emulates running a complex script auto r = script_invoke(ctx, f, arg); std::unique_lock lock(mx); result = r.value(); } cv.notify_all(); }; std::thread thr(helper, 10); thr.detach(); { std::unique_lock lock(mx); cv.wait(lock); } assert(result == 20); return 0; } Locks ----- The weak reference flag (``asILockableSharedBool*``) is lockable. The ``lockable_shared_bool`` class (documented in :doc:`../utility`) wraps the weak reference flag for use with ``std::lock_guard``. The AngelScript library provides global exclusive and shared locks. The wrappers for them are provided by the header ````. .. doxygenvariable:: asbind20::script_lock .. doxygenclass:: asbind20::script_lock_t :members: lock, unlock, lock_shared, unlock_shared Example code: .. code-block:: c++ { std::unique_lock lk(asbind20::script_lock); // Writing } .. code-block:: c++ { std::shared_lock lk(asbind20::script_lock); // Reading } Atomic Reference Counting ------------------------- .. _atomic-refcounting: .. doxygenclass:: asbind20::atomic_counter :members: :undoc-members: For garbage collected types, `please read the official document about thread safety and GC `_.