RubyLine C扩展-pthread_create调用ruby函数

RubyLine C扩展-pthread_create调用ruby函数,c,ruby,C,Ruby,我试图将C多线程应用于ruby方法,但无法正确调用ruby方法。我现在只测试一个线程,我不传递任何参数只是为了保持简单 这是密码 require 'inline' class ExampleThread def my_thread puts 'running thread'; end inline :C do |builder| builder.include "<pthread.h>" builder.c ' static VALUE run_

我试图将C多线程应用于ruby方法,但无法正确调用ruby方法。我现在只测试一个线程,我不传递任何参数只是为了保持简单

这是密码

require 'inline'

class ExampleThread

def my_thread
    puts 'running thread';
end

inline :C do |builder|
    builder.include "<pthread.h>"
    builder.c '
    static VALUE run_thread(void){
        ID my_thread    = rb_intern("my_thread");

        pthread_t pth;

        // normal ruby function call
        // rb_funcall(self, my_thread, 0);
        // but I want to try with threads
        pthread_create(&pth,NULL,my_thread,NULL);

        pthread_join(pth, NULL);

        return Qnil;
    }'
end

end
#=>编辑 阅读您的评论后,我决定更改代码,以下是我到目前为止的想法

require 'inline'

class Example

  inline :C do |builder|
  builder.include "<pthread.h>"

    builder.c '
    static void run_thread(VALUE name){
        // I added a ruby User class to test posting a variable from thread to db
        VALUE user = rb_const_get( rb_cObject, rb_intern("User") );         
        rb_funcall(user, rb_intern("add"), 1, name);
    }'


    builder.c '
    static void simple(VALUE name){
        run_thread(self, name);
    }'      


    builder.c '
    static void threads(VALUE name){
        pthread_t pth;

        pthread_create(&pth, NULL, (void *)run_thread, (VALUE *)name );

        pthread_join(pth, NULL);
    }'              
end     

end
如果我运行Example.new.simple(“Adam”),我会得到预期的结果

(0.3ms)  BEGIN
SQL (19.9ms)  INSERT INTO `users` (`created_at`, `name`, `updated_at`) VALUES ('2012-03-16 04:53:15', 'Adam', '2012-03-16 04:53:15')
(0.5ms)  COMMIT
(0.3ms)  BEGIN
SQL (19.9ms)  INSERT INTO `users` (`created_at`, `name`, `updated_at`) VALUES ('2012-03-16 04:53:15', 'Adam', '2012-03-16 04:53:15')
(0.5ms)  COMMIT
如果我运行Example.new.threads(“Adam”),就会得到错误

warning: passing argument 3 of ‘pthread_create’ makes pointer from integer without a cast
[FATAL] failed to allocate memory

我的理解是,为了得到预期的结果,我必须分配内存,但这个过程我不太清楚,我不知道如何实现它。

我不知道ruby。你提到的只是一个警告。因此将生成对象文件。运行它。它可能会像你期望的那样工作。警告说只是铸造问题。因此,显式地将我的_线程转换为一个空指针并编译。

我应该提到,我也遇到了一个分段错误。我厌倦了(void)并产生错误:void表达式的使用无效。ID my_thread=rb_intern(“my_thread”);我觉得这一行是一个函数调用,您将返回值分配回我的线程。如果我是正确的,那么对pthread_create的调用为false。您必须传递函数指针,而不是返回值。您需要传递c函数指针,而不是ruby方法名。我也不确定是否有一些每线程的设置,您需要为它与ruby运行时一起工作