Thread specific singleton's

L

List Recv

How do I make a thread specific Singleton?

That is, once instance per thread.

Related question: why do Singleton's use the Name.instance.method idiom
(using instance methods) as opposed to Name.method (using class
methods), which seems simpler and clearer.
 
R

Robert Klemme

List said:
How do I make a thread specific Singleton?

That is, once instance per thread.

Thread.current[:my_singleton_id] ||= whatever_creation_expression
Related question: why do Singleton's use the Name.instance.method
idiom (using instance methods) as opposed to Name.method (using class
methods), which seems simpler and clearer.

It's the typical way the singleton pattern works. Not all PL have Ruby's
flexibility with methods on class instances. Also you can still inherit
the class and have derived classes that do not use singleton pattern but
can still use super class methods. I probably missed something else.

Kind regards

robert
 
L

Logan Capaldo

How do I make a thread specific Singleton?

That is, once instance per thread.

Related question: why do Singleton's use the Name.instance.method
idiom
(using instance methods) as opposed to Name.method (using class
methods), which seems simpler and clearer.

def thread_singleton()
Thread.current["my singleton"] ||= MyOnePerThreadClass.new #
note, don't actually make MyOnePerThreadClass a "real" singleton
end

Then whenever you want to use the thread singleton in a given thread
use the thread_singleton function

e.g.:

Thread.start do
thread_singleton.send_some_message
end

Thread.start do
thread_singleton.send_other_message # a different singleton
for this thread than the other thread, but will be the same for the
duration of this thread
end

etc.


As far as your Name.method question, there's no particular reason not
to.. If you want you can implement a singleton like that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,649
Latest member
MargaretCo

Latest Threads

Top