Skip to content

Instantly share code, notes, and snippets.

@rtakacs
Created August 1, 2018 08:59
Show Gist options
  • Save rtakacs/3948e3294bb05fd9c74f1566f831c2ec to your computer and use it in GitHub Desktop.
Save rtakacs/3948e3294bb05fd9c74f1566f831c2ec to your computer and use it in GitHub Desktop.
JerryScript thread demo.
/**
* JerryScript thread example.
*
* Step 1: compile JerryScript
*
* tools/build.py --clean --jerry-libc=off --external-context=on --jerry-cmdline=off
*
* Step 2: compile this demo application
*
* gcc thread_demo.c -o thread_demo \
* -I<path-to-jerryscript>/jerry-core/include \
* -I<path-to-jerryscript>/jerry-ext/include \
* -L<path-to-jerryscript>/build/lib \
* -ljerry-ext -ljerry-core -ljerry-libm -ljerry-port-default -lpthread
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "jerryscript.h"
#include "jerryscript-ext/handler.h"
#define NUM_OF_THREADS 8
/* A different Thread Local Storage variable for each jerry instance. */
__thread jerry_instance_t* tls_instance;
jerry_instance_t *
jerry_port_get_current_instance (void)
{
/* Returns the instance assigned to the thread. */
return tls_instance;
}
/* Allocating JerryScript heap for each thread. */
static void *
instance_alloc_func(size_t size, void *cb_data)
{
(void) cb_data;
return malloc(size);
}
/* The concrete thread function. */
void *
thread_function(void *param)
{
int id = (int)(intptr_t)param;
printf("Thread (id: %d) started...\n", id);
/* Create a new JerryScript instance. */
tls_instance = jerry_create_instance (512 * 1024, instance_alloc_func, NULL);
const jerry_char_t script[64];
sprintf((char*)script, "print ('Hello World from thread %d!');", id);
jerry_init (JERRY_INIT_EMPTY);
/* Register a print function. */
jerryx_handler_register_global ((const jerry_char_t *) "print", jerryx_handler_print);
jerry_value_t parse_ret_val = jerry_parse (NULL, 0, script, strlen (script), JERRY_PARSE_NO_OPTS);
if (!jerry_value_is_error (parse_ret_val))
{
jerry_value_t run_ret_val = jerry_run (parse_ret_val);
jerry_release_value (run_ret_val);
}
jerry_release_value (parse_ret_val);
jerry_cleanup ();
return NULL;
}
int
main(void)
{
pthread_t threads[NUM_OF_THREADS];
/* Create the threads. */
for (int i = 0; i < NUM_OF_THREADS; i++) {
pthread_create(&threads[i], NULL, thread_function, (void*)(intptr_t)i);
}
/* Wait for the threads to complete, and release their resources. */
for (int i = 0; i < NUM_OF_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment