Created
June 16, 2009 20:05
-
-
Save jakedouglas/130860 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#include <ruby.h> | |
#include "thrqueue.h" | |
static VALUE cThreadTest; | |
void *produce(struct Queue *q) | |
{ | |
char *ptr = "foo"; | |
int i; | |
for (i=0; i < 10; i++) { | |
printf("producer pthread produced: %s\n", ptr); | |
queue_enq(q, ptr); | |
sleep(1); | |
} | |
} | |
void queue_free(struct Queue *q) | |
{ | |
while (!queue_empty(q)) | |
queue_deq(q); | |
queue_destroy(q); | |
} | |
static VALUE threadtest_init() | |
{ | |
struct Queue *q = queue_init(); | |
queue_limit(q, 10); | |
pthread_t thread; | |
pthread_create(&thread, NULL, produce, (void *)q); | |
return Data_Wrap_Struct(cThreadTest, NULL, queue_free, q); | |
} | |
static VALUE threadtest_consume(VALUE self) | |
{ | |
struct Queue *q = DATA_PTR(self); | |
char *ptr = queue_deq(q); | |
return rb_str_new2(ptr); | |
} | |
void Init_threadtest() | |
{ | |
cThreadTest = rb_define_class("ThreadTest", rb_cObject); | |
rb_define_singleton_method(cThreadTest, "new", threadtest_init, 0); | |
rb_define_method(cThreadTest, "consume", threadtest_consume, 0); | |
} | |
## ruby | |
require 'threadtest' | |
th = ThreadTest.new | |
while true | |
puts "consumer pthread consumed: #{th.consume}" | |
end | |
## output | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo | |
producer pthread produced: foo | |
consumer pthread consumed: foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment