c++ - CPP 线程中的嵌入式 Ruby 崩溃

标签 c++ ruby multithreading embed

我正在创建一个嵌入式 Ruby 框架,如果我正常/一次运行它就可以工作。当我尝试在线程循环中运行它时,程序崩溃了。

有效的例子:

我的Ruby文件.rb:

def helloworld()
    puts "Hello world"
end

工作 main.cpp:

#include <ruby.h>

void runRuby()
{
    ruby_init();
    ruby_init_loadpath();
    rb_require("myRubyfile");
    rb_funcall(rb_mKernel, rb_intern("helloworld"), 0 , NULL);
    ruby_finalize();
}

int main()
{
    runRuby();
    return 0;
}

上面的程序正确执行。

但是,我想在多个线程中运行多个 Ruby 脚本,下面的示例运行一次然后崩溃。

崩溃 main.cpp:

#include <ruby.h>
#include <thread>

void runRuby()
{
    ruby_init();
    ruby_init_loadpath();
    rb_require("myRubyfile");
    rb_funcall(rb_mKernel, rb_intern("helloworld"), 0 , NULL);
    ruby_finalize();
}

int main()
{
    for(int i = 0; i < 100; i++) {
        std::thread mythread(runRuby);
        mythread.join();
    }
    return 0;
}

我在 Windows 中运行它。

为什么会失败?

最佳答案

失败是因为 Ruby VM 不是线程安全的。您需要像在普通 Ruby 中一样使用 Ruby 的 Thread 类。 thread.c 具有您需要的大部分功能:

VALUE myThread(VALUE arg)
{
    // ...
}

int main()
{
    ruby_init();

    VALUE threads[100];

    for(int i = 0; i < 100; ++i)
        threads[i] = rb_thread_create(RUBY_METHOD_FUNC(myThread), Qnil);

    for(int i = 0; i < 100; ++i)
        rb_funcall(threads[i], rb_intern("join"), 0);

    return ruby_cleanup(0);
}

由于 Ruby 的线程不是真正并行的,真正并行加载和运行脚本的唯一方法是在不同的子进程中启动多个虚拟机。

关于c++ - CPP 线程中的嵌入式 Ruby 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488029/

相关文章:

C++ - 可以在 OpenCV 中使用 Vec3b 的一些解释

c++ - 在 C++ 中使用 auto 的最简单示例是什么?

c++ - C++ 中用于 size_t 类型的 ceil() 和 floor() 函数

ruby - 在 Chef 中更改 ruby​​_block 中的权限时如何执行 "unless"条件?

ruby-on-rails - Ruby on Rails 同时发出多个 HTTP 请求?

java - 这个 "synchronized"可以工作吗?

c++ - 反转 vector 并打印它

ruby - 如何打印 Ruby 对象的内存位置

android - 等待 TextToSpeech onInit() 初始化

.NET 或 Windows 同步原语性能规范