CPP线程中嵌入的Ruby崩溃
Embeded Ruby in a CPP thread crashes
我正在创建一个嵌入式Ruby框架,如果我正常/一次运行它,它就会工作。当我试图在线程循环中运行它时,程序会崩溃。
工作示例:
myRubyfile.rb:
def helloworld()
puts "Hello world"
end
工作主.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虚拟机不是线程安全的。您需要像使用普通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的线程并不是真正并行的,所以真正并行加载和运行脚本的唯一方法是在不同的子流程中启动多个VM。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 递归列出所有目录中的C++与Python与Ruby的性能
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么要增加导致崩溃的指针
- 在虚幻引擎中删除NXOpen对象时崩溃
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 使用 VS2010 IDE 生成的 Ruby 的 SWIG 包装器 DLL 崩溃
- CPP线程中嵌入的Ruby崩溃