• Stars
    star
    1,049
  • Rank 42,205 (Top 0.9 %)
  • Language
    C++
  • License
    MIT License
  • Created about 3 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿงต Fast and easy multithreading for React Native using JSI

Installation

npm install react-native-multithreading
npx pod-install

Since JSI is not officially released, installing react-native-multithreading requires you to edit a few native files. See the setup guide (SETUP.md) for more details.

Requires react-native-reanimated 2.1.0 or higher.

๐ŸŽ‰ v1.0 with Android support is here! ๐ŸŽ‰

Why

Since JSI is becoming more mainstream, there might be functions that are actually blocking and take a while to execute. For example, a storage library like my react-native-mmkv or an SQLite JSI library might take a few milliseconds to execute a complex call. You don't want your entire React-JS thread to freeze when doing that, since users will perceive a noticeable lag or freeze.

That's where react-native-multithreading comes in; you can simply off-load such expensive calculations/blocking calls to a separate thread with almost no overhead while your main React-JS thread can concentrate on running your app's business logic, respond to user input, update state and more. You can also run complex JS calculations such as the Fibonacci number, but that's probably a rare use-case.

Inspired by @karol-bisztyga's Multithreading PR for Reanimated

Usage

To try out the Fibonacci Example, clone the repo and run the following commands:

yarn bootstrap
cd example
yarn ios

See my tweet ๐Ÿฆ

Shoot and Forget

To simply perform an expensive calculation on another thread without caring about the result, use the spawnThread function:

// JS thread
spawnThread(() => {
  'worklet'
  // custom thread
  // expensive calculation
})
// JS thread

The React-JS Thread will continue execution while the custom thread will run the given function on a custom parallel runtime.

Await

Since spawnThread returns a Promise, you can also await the result. The React-JS Thread will not be blocked and will still be able to continue execution elsewhere (timers, callbacks, rendering, ...), while the custom thread runs the given function in a custom parallel runtime.

const result = await spawnThread(() => {
  'worklet'
  // expensive calculation
  return ...
})

Fibonacci

This example calculates the Fibonacci Number for the given input. This demonstrates expensive calculation, awaiting the result, as well as using values from "outside". (fibonacci function and input are captured into the new thread and therefore immutable.)

const fibonacci = (num: number): number => {
  'worklet'
  if (num <= 1) return 1
  return fibonacci(num - 1) + fibonacci(num - 2)
}

const input = 50
const result = await spawnThread(() => {
  'worklet'
  console.log(`calculating fibonacci for input: ${input} in JS-Runtime: ${global._LABEL}...`)
  const fib = fibonacci(input)
  console.log("finished calculating fibonacci!")
  return fib
})
console.log(`Fibonacci Result: ${result}`)

What's possible?

  • You can run any JavaScript code you want in there.
  • You can use variables from "outside" (e.g. state), but those will be immutable/frozen.
  • You can use functions from "outside".
    • Worklets (functions with the 'worklet' directive) can be called directly on the separate thread
    • Native JSI functions ("host functions", aka functions that print function f() { [native code] } when you call .toString() on them) can be called synchronously (e.g. functions from react-native-mmkv)
    • Normal JS functions (e.g. setState) can be called on the React-JS thread with runOnJS
  • You can assign Reanimated Shared Values.

Note that react-native-multithreading is more of a proof of concept than a production ready library. Everything works as I listed it here, but in real world app you most likely won't be needing a JS multithreading library.

What's not possible?

  1. Since the library uses JSI for synchronous native methods access, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use Flipper.
  2. All functions you are calling inside a custom thread, must be workletized to truly run on a separate thread. So add the 'worklet' directive at the top of every function you're calling in that thread (including the thread callback itself), and don't forget to install the Reanimated babel plugin.

Supported JS engines

  • JavaScript Core (JSC)
  • Hermes
  • V8 (iOS only)

Performance

Since the worklets are completely dispatched in an isolated thread, nothing interrupts their execution.

Be aware that there always will be a small overhead when calling spawnThread, because all variables from outside have to be copied into the new thread first. For example, if you use the separate thread to do complex array operations, be aware that the array has to be copied into the separate thread first. Always benchmark the performance differences!

Credits

Note: Technically this is not multithreading, but rather multiprocessing.

More Repositories

1

react-native-vision-camera

๐Ÿ“ธ A powerful, high-performance React Native Camera library.
Swift
6,320
star
2

react-native-mmkv

โšก๏ธ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!
C++
4,903
star
3

react-native-blurhash

๐Ÿ–ผ๏ธ A library to show colorful blurry placeholders while your content loads.
Kotlin
1,568
star
4

Colorwaver

๐ŸŽจ An app to detect color palettes in the real world - powered by VisionCamera
TypeScript
548
star
5

react-native-jsi-image

๐Ÿ–ผ๏ธ A writeable in-memory Image JSI Host Object
C++
267
star
6

react-native-tracking-transparency

๐Ÿ•ต๏ธ A React Native Library for interacting with the tracking API from iOS 14.
Java
208
star
7

react-native-google-nearby-messages

๐Ÿ“ฒ Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!
Kotlin
173
star
8

react-native-jsi-contacts

A contacts library for React Native using JSI
C++
140
star
9

AnimatedGif

๐Ÿ“ผ A high performance .NET library for reading and creating animated GIFs
C#
127
star
10

react-native-blob-jsi-helper

A React Native library for accessing an ArrayBuffer of a Blob instance.
C++
118
star
11

react-native-jsi-library-template

Template for React Native JSI Libraries ร  la Marc
C++
110
star
12

clean-rn

A simple CLI tool to clean all React Native caches in your project.
JavaScript
109
star
13

vision-camera-image-labeler

VisionCamera Frame Processor Plugin to label images using MLKit Vision
Java
97
star
14

ImgurSniper

๐Ÿ“ท A quick and easy Image, Screenshot and Screen recording sharing tool
C#
85
star
15

react-native-style-utilities

Fully typed hooks and utility functions for the React Native StyleSheet API
JavaScript
78
star
16

Hotkeys

๐Ÿ”ค A small C# (.NET) Library which allows binding of global HotKeys to any Application's Windows (including Windows Apps such as explorer.exe), even in Background. (using P/Invokes)
C#
71
star
17

react-native-notification-badge

๐Ÿ”ด A notification badge count manager for React Native
Swift
47
star
18

react-native-pressable-opacity

A <PressableOpacity> and a supercharged <NativePressableOpacity> components for React Native
TypeScript
46
star
19

GenericProtocol

โšก๏ธ A fast TCP event based buffered server/client protocol for transferring data over the (inter)net in .NET ๐ŸŒ
C#
42
star
20

DiscordMusicBot

A Discord Bot for playing YouTube music.
C#
41
star
21

react-native-pressable-scale

A <PressableScale> and a supercharged <NativePressableScale> components for React Native
TypeScript
39
star
22

StorageBenchmark

Benchmark App to compare different storage libraries (MMKV, AsyncStorage, WatermelonDB, RealmDB, SQLite)
Java
29
star
23

react-native-screen-corner-radius

๐Ÿ“ฑ A React Native library to get the Device's Screen's corner radius
Java
27
star
24

BrabeNetz

๐Ÿง  A fast and clean supervised neural network in C++, capable of effectively using multiple cores
C++
26
star
25

Toast

๐Ÿž The rounded and animated Android Toast for .NET WPF/XAML
C#
26
star
26

Fiddle

๐Ÿ“œ A lightweight code editor for editing, compiling and running code snippets/scripts supporting multiple languages and rich GUI
C
23
star
27

Jellyfish

๐ŸŸ An incredibly lightweight and type safe MVVM library for .NET WPF, Silverlight, Xamarin and UWP
C#
20
star
28

PostShot

๐Ÿ“ท An easy to use, lightning fast and modern screenshot and screen-recording tool powered by C++ and Qt
C++
17
star
29

vision-camera-resize-plugin

A VisionCamera Frame Processor plugin for fast buffer resizing
Objective-C
17
star
30

WebUntisSharp

โฐ A Wrapper of the WebUntis JSON API for .NET
C#
14
star
31

pipestate

๐Ÿฆ A minimal state management library for React.
TypeScript
13
star
32

gimp-rpc

A GIMP plugin to display Discord Rich Presence made with C
C
11
star
33

react-native-sectioned-slider

An iOS 11 Control Center inspired Slider for React Native
Ruby
10
star
34

ClipboardMonitor

A small C# Library for Monitoring Clipboard with P/Invokes (e.g.: Clipboard Content Changed event)
C#
9
star
35

GameFinder

๐ŸŽฎ An application for finding games to play you and your friends have on Steam
C#
8
star
36

QHotkeys

๐Ÿ”  A small and lightweight cross platform C++ library implementing a system-wide hotkey system for Qt
C++
7
star
37

Keepr

A Tinder-like swipe view to keep or remove pictures from a photoshoot with extra comparison features
TypeScript
7
star
38

BmpPwd

๐Ÿ” BmpPwd is a .NET Class Library for overloadable en/decrypting strings or binary data to a System.Drawing.Image
C#
7
star
39

MaterialDesignWindowsDialogs

A new Theme (Android Material Design) for Windows Message Boxes (by hooking)
C#
7
star
40

shared-registry

Shared-Registry allows you to share objects between instances without introducing memory leaks.
TypeScript
6
star
41

dotfiles

My personal minimalistic dotfiles (.vimrc, .zshrc, .oh-my.zsh, custom scripts, ..)
Shell
6
star
42

mrousavy

โœจ it's lit โœจ
6
star
43

MetaLog

๐Ÿ“ Simple, yet effective, logging with Metadata CallerInfo for creating beautiful Log files in C#/VB .NET
C#
5
star
44

SchoolTool

๐Ÿ““ An App to watch your timetable and get notified of changes.
C#
3
star
45

HankHill

A discord bot for pixelating and jpegifying images
C#
3
star
46

maconvert

Easily convert .svg files to .png files
JavaScript
3
star
47

TinyRocket

A 2D Endless Unity Game; Fly up high and beat highscores with your customizable and upgradeable Rocket!
C#
3
star
48

Cirilla

๐Ÿค– Cirilla - The swiss army knife discord bot supporting many commands and systems
C#
3
star
49

Morph

๐Ÿ›  A fast .NET Standard Class Library for parsing results from an SQL query to .NET objects to eliminate risky column-index hardcoding
C#
2
star
50

QPastebin

A quick Pastebin-uploader shell script using curl and the Pastebin REST API
Shell
2
star
51

QuantumSnippets

Snippets, Examples or Test code for Quantum Computers written in the Microsoft Quantum Computer Programming Language Q#
C#
1
star
52

discord-cli

CLI for discord bots
JavaScript
1
star
53

ModellbaumesseRoboter

Roboter fรผr Modellbaumesse 2016 (TGM 3DHIT)
C++
1
star
54

Vertaler

๐Ÿ“– A pop-up tray application to instantly translate something from your clipboard using Google Translate
C#
1
star
55

pokecord-guesser

Guesser for Pokecord using Discord API and reverse image lookup
HTML
1
star
56

ModWnd

๐Ÿ‘บ A daemon to move any Window from within it's body (child area) while holding a modifier key (Windows/Alt)
C++
1
star
57

VisionCameraDemo

Demo for using VisionCamera + zooming
TypeScript
1
star