Skip to content

Threading in C++

CppInator includes support for the pthreads library, which provides a simple API for creating and managing threads in C++. To use pthreads in your C++ scripts, you need to include the pthread.h header file and link against the pthread library.

Windows is also supported.

Here is an example of creating a new thread in C++ using pthreads:

#include <pthread.h>

void* myThread(void* arg)
{
    pthread_exit(NULL);
}

int main()
{
    pthread_t thread;
    pthread_create(&thread, nullptr, myThread, nullptr);
    pthread_join(thread, nullptr);
    return 0;
}

You could for example callback a C# function from the new thread:

#include <unityengine.h>

typedef void (*MyFancyCallback)(int);


void* myThread(void* arg)
{
    CallMeBaby((MyFancyCallback)arg);
    pthread_exit(NULL);
}

EXPORT(void) StartAThreadMethod(MyFancyCallback callback)
{
    pthread_t thread;
    pthread_create(&thread, nullptr, myThread, (void*)callback);
}

Be careful when calling Unity API from a new thread, as Unity API is not thread-safe. You should only call Unity API from the main thread. To call a Unity API from a new thread, you can use the UnityMainThreadDispatcher class provided by CppInator.

void* myThread(void* arg)
{
    auto callback = (MyFancyCallback)arg;
    int calculateNumber = 0;

    for (int i = 0; i < 1000000; i++)
        calculateNumber += i;

    QueueToMainThread([]() {
        callback(calculateNumber);
    });

    pthread_exit(NULL);
}

QueueToMainThread is a function provided by CppInator that queues a lambda function to be executed on the main thread. This allows you to safely call Unity API from a new thread.