Skip to content

Instantly share code, notes, and snippets.

@paddor
Last active December 27, 2015 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paddor/53e2820e49df04b3eec0 to your computer and use it in GitHub Desktop.
Save paddor/53e2820e49df04b3eec0 to your computer and use it in GitHub Desktop.
Rubinius: can't spawn a Thread from within an FFI::Function if the FFI::Function is called from another thread
#include "callback.h"
#include <pthread.h>
#include <assert.h>
#include <stdlib.h>
static void *
s_thread_shim (void *args)
{
assert (args);
callback_fn* callback = (callback_fn *) args;
printf("libcallback: calling callback at %p ...\n", callback);
(* callback)();
printf("libcallback: callback %p has returned.\n", callback);
return NULL;
}
void
call_callback(callback_fn *callback)
{
pthread_t thread;
pthread_create (&thread, NULL, s_thread_shim, callback);
pthread_detach (thread);
}
#ifndef __CALLBACK_BUG_H_INCLUDED__
#define __CALLBACK_BUG_H_INCLUDED__
#include <stdio.h>
typedef void (callback_fn) (void);
void
call_callback(callback_fn *callback);
#endif
libcallback.dylib: callback.h callback.c
clang -dynamiclib -std=gnu99 callback.c -o $@
require 'ffi'
module Callback
extend ::FFI::Library
lib_name = 'libcallback'
ffi_lib "#{lib_name}.#{::FFI::Platform::LIBSUFFIX}"
attach_function :call_callback, [:pointer], :void, blocking: true
end
ffi_function = FFI::Function.new(:void, [], blocking: true) do
puts "BEGIN ffi_function"
Thread.new do
puts "hello from inner thread"
end
puts "END ffi_function"
end
Callback.call_callback(ffi_function)
sleep 1
__END__
###
# EXPECTED:
# Output on CRuby 2.2.4:
libcallback: calling callback at 0x10242b000 ...
BEGIN ffi_function
END ffi_function
libcallback: callback 0x10242b000 has returned.
hello from inner thread
###
# ACTUAL
# Output on Rubinius 2.8.5
libcallback: calling callback at 0x1088eb000 ...
BEGIN ffi_function
libcallback: callback 0x1088eb000 has returned.
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment