#include "Python.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

static PyThreadState* main_state;

void *on_thread(void *vargp){
    PyEval_AcquireThread(main_state);
    PyThreadState* state = Py_NewInterpreter();
    PyRun_SimpleString("print('In a sub interpreter')\n");
    Py_EndInterpreter(state);
    PyThreadState_Swap(main_state);
    PyEval_ReleaseThread(main_state);
    return NULL;
}

int main() {
    Py_SetProgramName(L"./_testembed");
    Py_DontWriteBytecodeFlag = 1;
    Py_Initialize();
    main_state = PyThreadState_Get();
    PyRun_SimpleString("print('Before creating sub interpreter')\n");
    Py_BEGIN_ALLOW_THREADS

    pthread_t thread_id;
    pthread_create(&thread_id, NULL, on_thread, NULL);
    pthread_join(thread_id, NULL);

    Py_END_ALLOW_THREADS
    PyRun_SimpleString("print('After running sub interpreter')\n");
    Py_Finalize();

    exit(0);
}

