Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Last active December 30, 2015 04:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanlilmateus/7777282 to your computer and use it in GitHub Desktop.
Save seanlilmateus/7777282 to your computer and use it in GitHub Desktop.
THREAD-SAFETY for every one... simple way to wrap any object with a thread-safe wrapper,
class << NSProxy
def method_added(meth)
end
def inherited(klass)
end
end
class Proxy < NSProxy
def self.const_missing(n)
::Object.const_get(n)
end
def self.new(object=nil)
alloc.initWithTarget(object)
end
def initWithTarget(target)
@_target = target
@_queue = Dispatch::Queue.new("#{target.object_id}-de.mateus.synchronized.proxy")
self
end
def method_missing(m, *args, &blk)
@_queue.sync do
options = args.select { |arg| arg.is_a?(::Hash) }.first
selector = arguments = nil
if options
selector = options.keys.unshift(m).map { |txt| txt.to_s.appendString(':') }.join
arguments = options.values.unshift(args.first)
end
target = @_target
result = if selector && target.respond_to?(selector)
target.__send__(selector, *arguments, &blk)
elsif target.respond_to?(m)
target.__send__(m, *args, &blk)
end
return result
end
end
def inspect
description
end
end
# let try create an dumbass parallel the map
class Array
def failed_map(&block)
return self.to_enum unless block_given?
result = []
Dispatch::Queue.concurrent.apply(self.count) { |idx| result << block.call(self[idx]) }
NSArray.arrayWithArray(result)
end
def p_map(&block)
return self.to_enum unless block_given?
result = Proxy.new([])
Dispatch::Queue.concurrent.apply(self.count) { |idx| result << block.call(self[idx]) }
NSArray.arrayWithArray(result.to_a)
end
end
array = [*0...1000]
result = array.p_map { |obj| obj + 10 }
puts result.count # => 1000
result = array.failed_map { |obj| obj + 10 }
puts result.count # => it might returns an shit, you never know.... 988 | 987 | 980... 1000 possibilities
# it may even crash...
# let's try out a named parameters method... boommmm every thing works
content = Proxy.new([*0..1000])
opts = NSEnumerationConcurrent|NSEnumerationReverse
content.enumerateObjectsWithOptions(opts, usingBlock:-> obj, idx, stop { puts "#{idx}:\t#{obj}\n" })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment