RubyInline C扩展--pthread_create调用ruby函数

时间:2012-03-12 04:16:15

标签: 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_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

这是错误

warning: passing argument 3 of ‘pthread_create’ makes pointer from integer without a cast

#=&gt;修改

阅读你的评论我决定改变代码,这是我到目前为止所提出的。

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.run_thread(“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

如果我运行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

如果我运行Example.new.threads(“Adam”),我会收到错误

[FATAL] failed to allocate memory

我的理解是我必须得到ALLOC记忆以获得预期的结果,但这个过程对我来说不是很清楚,我不知道如何实现它。

1 个答案:

答案 0 :(得分:0)

我不喜欢红宝石。你提到的只是一个警告。因此将生成目标文件。运行。它可能正如您预期的那样正常工作。警告说只是一个铸造问题。所以显式地将my_thread转换为void指针并编译。