Skip to content

Commit

Permalink
add fine-grained operation to control V8 Platform instance lifecycle.
Browse files Browse the repository at this point in the history
  • Loading branch information
LanderlYoung committed May 27, 2023
1 parent 9ba84d5 commit b4c1c19
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
26 changes: 26 additions & 0 deletions backend/V8/V8Helper.hpp
Expand Up @@ -97,6 +97,32 @@ struct v8_interop {
static ArgumentsData extractArguments(const Arguments& args) {
return ArgumentsData{args.callbackInfo_.first, args.callbackInfo_.second};
}

struct Critical {
/**
* DANGEROUS OPERATION!!!
* By default the v8 platform is a process-level singleton, which will be destroyed during
* process exit. In some C++ guide, it's recommended not to relay on static variable
* destruction.
*
* By call this method, it is guaranteed not to destroy the platform instance (actually by
* making the singleton leak).
*/
static void neverDestroyPlatform();

/**
* DANGEROUS OPERATION!!!
* By default the v8 platform is a process-level singleton, which will be destroyed during
* process exit. In some case, if you are sure not to use V8 in the process again (never
* re-create a instance), you can call this method to destroy the platform immediately. Once
* destroyed, V8 usually shuts down thread pool, etc to release resources.
*
* In face, if there is still running V8Engine instance, the platform will be destroy
* afterwords.
*
*/
static void immediatelyDestroyPlatform();
};
};

} // namespace script
17 changes: 17 additions & 0 deletions backend/V8/V8Platform.cc
Expand Up @@ -17,8 +17,10 @@

#include "V8Platform.h"
#include <libplatform/libplatform.h>
#include <type_traits>
#include "../../src/Utils.h"
#include "V8Engine.h"
#include "V8Helper.hpp"

namespace script::v8_backend {

Expand Down Expand Up @@ -198,3 +200,18 @@ bool V8Platform::OnCriticalMemoryPressure(size_t length) {
#endif

} // namespace script::v8_backend

void script::v8_interop::Critical::neverDestroyPlatform() {
using script::v8_backend::V8Platform;
auto platform = V8Platform::getPlatform();

// make the shared_ptr leak
std::aligned_storage_t<sizeof(std::shared_ptr<V8Platform>)> buffer;
new (&buffer) std::shared_ptr<V8Platform>(platform);
}

void script::v8_interop::Critical::immediatelyDestroyPlatform() {
using script::v8_backend::V8Platform;
std::lock_guard<std::mutex> lock(V8Platform::lock_);
V8Platform::singletonInstance_ = nullptr;
}
2 changes: 2 additions & 0 deletions backend/V8/V8Platform.h
Expand Up @@ -144,6 +144,8 @@ class V8Platform : public v8::Platform {
void addEngineInstance(v8::Isolate* isolate, V8Engine* engine);

void removeEngineInstance(v8::Isolate* isolate);

friend struct script::v8_interop;
};

} // namespace script::v8_backend

0 comments on commit b4c1c19

Please sign in to comment.