Search code examples
v8embedded-v8

Wanting to understand purpose and count of V8's WorkerThread(s)


I have a very simple program as follows that just creates an isolate, then sleeps:

#include <libplatform/libplatform.h>
#include <v8-platform.h>
#include <v8.h>

#include <stdio.h>
#include <unistd.h>

using v8::Isolate;

int main() {

   std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
   v8::V8::InitializePlatform(platform.get());
   v8::V8::Initialize();

   v8::Isolate::CreateParams create_params;
   create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
   Isolate* isolate = v8::Isolate::New(create_params);

   printf("Sleeping...\n");
   usleep(1000 * 1000 * 100);
   printf("Done\n");
   return 0;
}

When i run this program, i can then check the number of threads the process has created with ps -T -p <process_id>, and i see that on my 8 core machine, v8 creates 7 extra threads all named "V8 WorkerThread", and on my 16 core machine i get 8 instances of this "V8 WorkerThread" created.

I am looking to understand what determines the number of extra threads v8 spawns and what the purpose of these threads are. Thanks in advance!


Solution

  • The number of worker threads, when not specified by the embedder (that's you!), is chosen based on the number of CPU cores. In the current implementation, the formula is: number_of_worker_threads = (number_of_CPU_cores - 1) up to a maximum of 8, though this may change without notice. You can also specify your own worker thread pool size as an argument to NewDefaultPlatform.

    The worker threads are used for various tasks that can be run in the background, mostly for garbage collection and optimized compilation.