Skip to content

Instantly share code, notes, and snippets.

@tomotaka
tomotaka / SyncCyclicIterator.rb
Created July 13, 2011 02:58
cyclic iterator for multithread
class SyncCyclicIterator
def initialize(ary)
@ary = ary
@mtx = Mutex.new
@idx = 0
end
def next
ret = nil
@mtx.synchronize do
@tomotaka
tomotaka / ex_resource_lock.rb
Created July 13, 2011 02:59
offering exclusive locking resources for multithread
class ExResourceLock
def initialize(map)
@rmap = map
@mtx = Mutex.new
@cv = ConditionVariable.new
@mtx.synchronize do
@free_resources = @rmap.keys
@locked_resources = []
end
@tomotaka
tomotaka / concurrent_executor.rb
Created July 13, 2011 03:03
offers concurrent execution method to Enumerable object
module ConcurrentExecutor
def concurrent_each(concurrency, queue_size, &proc)
require "thread"
queue = SizedQueue.new(queue_size)
queueing_thread = Thread.start{
each{|item| queue.enq([item, true]) }
concurrency.times{ queue.enq([nil, false]) } # send termination signal
}
@tomotaka
tomotaka / cyclic_iterator.rb
Created July 14, 2011 07:31
simple cyclic iterator(cannot be used on multithread environment)
class CyclicIterator
def initialize(collection)
@collection = collection
@i = 0
end
def next
item = nil
item = @collection[@i]
# usage: ruby ./random-kun.rb aaa bbb ccc ddd
srand
puts ARGV[rand(ARGV.size)]
@tomotaka
tomotaka / Channel.java
Created November 9, 2011 08:41
feed-subscriber model messaging
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
public class Channel<E> {
private final Map<UUID, LinkedBlockingQueue<E>> channels = new HashMap<UUID, LinkedBlockingQueue<E>>();
# to parse datetime expression like: "2012-01-01 24:00:01"
def my_time_parse(str)
y, m, d, hour, min, sec = str.split(/[^0-9]/).map{|x| x.to_i }
base = Time.local(y, m, d)
return (base + (hour*60*60 + min*60 + sec))
end
@tomotaka
tomotaka / picklefunc.py
Created June 16, 2012 08:54
callable can be pickled
import pickle
def hoge(n):
n2 = n * 2
print "this is hoge, n*2=%d" % n2
s_hoge = pickle.dumps(hoge)
loaded_hoge = pickle.loads(s_hoge)
@tomotaka
tomotaka / tornadooption.py
Created June 27, 2012 08:27
tornadooption.py
# using https://github.com/tomotaka/msgpack-rpc-python/commit/9a116f7255a5d6c2f773ee48225cd05173b7916b
import tornado.web
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import msgpackrpc
import msgpackrpc.loop
@tomotaka
tomotaka / with_normal_msgpack_rpc_python.py
Created June 27, 2012 08:53
with_normal_msgpack_rpc_python.py
# perform async MessagePack RPC request
# base idea is from: https://github.com/msgpack/msgpack-rpc-python/pull/5
import tornado.web
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import msgpackrpc
import msgpackrpc.loop