Forum: Ruby Thread specific singleton's

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ccfe7d097475a32dc3ff78d6fc42c852?d=identicon&s=25 List Recv (lstrecv)
on 2005-12-19 08:12
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.
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2005-12-19 09:55
(Received via mailing list)
List Recv wrote:
> 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
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2005-12-19 10:04
(Received via mailing list)
On Dec 19, 2005, at 2:12 AM, List Recv wrote:

> Posted via http://www.ruby-forum.com/.
>

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.
This topic is locked and can not be replied to.