accessing a class instance from a separate class running in a separate thread

  • Thread starter Thread starter titan nyquist
  • Start date Start date
T

titan nyquist

I have a class with data and methods that use it. Everything is
contained perfectly

THE PROBLEM: A separate thread has to call a method in the current
instantiation of this class. There is only ever ONE instantiation of
this class, and this outside method in a separate thread has to access
it.

How do i do this?

POSSIBLE SOLUTION: Have a static pointer to the class that is updated
to point to the current instantiation. The downside to this, is I
must the outside thread is not calling the method when the class is
not instantiated.

POSSIBLE SOLUTION #2: Make it a static class, as there's only ever
one instance of it at any given point in time. The downside to this,
is the data should be cleared away for when each new instance was
created, and instead of worrying about resetting old data, I made the
class require instantiation so each instance has its own fresh data.

What do you think?
 
- make sure your class is thread safe

- this class must implement the singleton pattern (since there's always
one and only one instance)

- The singleton must have a static method / property returning the
current instance (and create it if none exists)

- Everywhere in your code, always use this method / property to access
the instance. Never use nor store any variable on it.
 
Can you point me to more information on "the singleton pattern" and
singletons?

Titan
 
Can you point me to more information on "the singleton pattern" and
singletons?

of course :
The Singleton is a Desing Pattern. Design patterns are very useful
"recipes" that are working fine. You can adapt them depending on your
needs, languages, etc.
One of the most known book about DP in computing is the one of "the
gang of four", Erich Gamma is the most known of the "gang".
From this book (c++ is used in the book but that's working the same in
any OOP language, of course in C#, just more readable in C# :-) ) :

(I give you some C# examples at the end of this post)

Intent
------
Ensure a class only has one instance, and provide a global point of
access to it.

Motivation
----------
It's important for some classes to have exactly one instance. Although
there can be many printers in a system, there should be only one
printer spooler. There should be only one file system and one window
manager. A digital filter will have one A/D converter. An accounting
system will be dedicated to serving one company.

How do we ensure that a class has only one instance and that the
instance is easily accessible? A global variable makes an object
accessible, but it doesn't keep you from instantiating multiple
objects.

A better solution is to make the class itself responsible for keeping
track of its sole instance. The class can ensure that no other instance
can be created (by intercepting requests to create new objects), and it
can provide a way to access the instance. This is the Singleton
pattern.

Applicability
-------------
Use the Singleton pattern when

* there must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point.

* when the sole instance should be extensible by subclassing, and
clients should be able to use an extended instance without modifying
their code.

Participants
------------
* Singleton

-defines an Instance operation that lets clients access its unique
instance. Instance is a class operation (that is, a class method in
Smalltalk and a static member function in C++).

-may be responsible for creating its own unique instance.


Collaborations
--------------
Clients access a Singleton instance solely through Singleton's Instance
operation.

Consequences
------------
The Singleton pattern has several benefits:

*Controlled access to sole instance. Because the Singleton class
encapsulates its sole instance, it can have strict control over how and
when clients access it.

*Reduced name space. The Singleton pattern is an improvement over
global variables. It avoids polluting the name space with global
variables that store sole instances.

*Permits refinement of operations and representation. The Singleton
class may be subclassed, and it's easy to configure an application with
an instance of this extended class. You can configure the application
with an instance of the class you need at run-time.

*Permits a variable number of instances. The pattern makes it easy to
change your mind and allow more than one instance of the Singleton
class. Moreover, you can use the same approach to control the number of
instances that the application uses. Only the operation that grants
access to the Singleton instance needs to change.

*More flexible than class operations. Another way to package a
singleton's functionality is to use class operations (that is, static
member functions in C++ or class methods in Smalltalk). But both of
these language techniques make it hard to change a design to allow more
than one instance of a class. Moreover, static member functions in C++
are never virtual, so subclasses can't override them polymorphically.


Implementation
--------------
Here are implementation issues to consider when using the Singleton
pattern:

* Ensuring a unique instance. The Singleton pattern makes the sole
instance a normal instance of a class, but that class is written so
that only one instance can ever be created. A common way to do this is
to hide the operation that creates the instance behind a class
operation (that is, either a static member function or a class method)
that guarantees only one instance is created. This operation has access
to the variable that holds the unique instance, and it ensures the
variable is initialized with the unique instance before returning its
value. This approach ensures that a singleton is created and
initialized before its first use.

You can define the class operation in C++ with a static member function
Instance of the Singleton class. Singleton also defines a static member
variable _instance that contains a pointer to its unique instance.

The Singleton class is declared as

class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};

-------------------
C# example :

here: http://www.yoda.arachsys.com/csharp/singleton.html

another one here :
http://www.c-sharpcorner.com/Upload...Pattern12052005063955AM/SingletonPattern.aspx
 
Ok, I understand what singletons are now, which is basically a class
that only allows one instance of itself.

But, will this work for me? I must destuct the instance that exists,
every so often, and the create a new one. In c#, since it takes care
of when the old one is destructed, I cannot make sure it is gone
before I make a new one. I know there's ways to manual take back
control of destruction of class instances, but I am new to c#, and I'm
not sure if tha'ts a good idea or not. A better idea maybe just
allowing multiple instances to exist, but making sure outside thread
code only ever accesses the latest or more current one...

Either way, if I use a singleton or allow multiple instances, I only
want to access the lastest instance from this outside thread... and
there seems to be no great way to ensure synchronization. There is
always that chance that this ouside thread is pointing to the wrong
class (an older instance) due to delays in processing.

Titan
 
Unfortunately the latter page doesn't give a thread-safe version,

that's true, but why speaking about the second and not the first that
is showing a thread safe implementation...

It was, as I said it, 'examples'. Just to show a few ways to implement
the pattern.
There is not a 'legal' and 'unique' way to implement each design
pattern, each developer has his/her own way, and certainly, the
Singleton is the one with the most numerous versions..
 
But, will this work for me? I must destuct the instance that exists,
every so often, and the create a new one. ....
not sure if tha'ts a good idea or not. A better idea maybe just
allowing multiple instances to exist, but making sure outside thread
code only ever accesses the latest or more current one...


I'm not sure to understand your real need, so it's hard to give you an
advice on the better way...
If your code must always access the 'latest' version, then why not
using 'one' version (since the preceding are useless) ?
If your class is using some external resources needing to be released,
then just add a method to kill these resources and go on with only one
instance.
There is something strange, like a paradox, wanting a unique instance
and, in the same time, wanting to kill it after each use.
But, as I said it, I don't really understand your need here, so if you
can explain a bit more..
 
OD said:
that's true, but why speaking about the second and not the first that
is showing a thread safe implementation...

Because I wrote the first one and have no problems with it :)

All I'm saying is that the second article isn't a particularly good
one, but that may well not be obvious to a reader.
It was, as I said it, 'examples'. Just to show a few ways to implement
the pattern.
There is not a 'legal' and 'unique' way to implement each design
pattern, each developer has his/her own way, and certainly, the
Singleton is the one with the most numerous versions..

Yes, and a lot of them aren't thread-safe - why bother referring to
flawed examples?
 
OD,

Here's a simplified example of what I am trying to do:

I am analysing data coming to me from an Internet source. I have to
read this data in and analyze it. The data I create from the analysis
should only for the time period I am analyzing the data. I eventually
stop (stops are not predefined, they essentially happen randomly) and
move onto the next time period. I have to make sure I clean out the
data from previous time period when I move on to the next.

Instead of cleaning out old data from a static class, I thought why
not use instances? Then, each time period has its own data. No
confusion.

The problem... however... is the incoming data is from another thread,
which must access this class to input the data into it. During switch-
over from one instance to the next (whether it is a singleton class or
not), the data might be pointing to the wrong instance (or might be
pointing to null)!

I solved this by creating a global reference to the current instance.
The class constructor sets this global reference to point to itself,
and it points it to null when it quits. Then, I made the incoming
data make sure it is not null by handling a NullReferenceException, as
it should never happen at all (if you really knew what my program was
doing you would see this).

I still made this outside thread handle a NullReferenceException,
because it is dependant on a variable to point to a class that it has
no control over. It would be unfair (and not robust) to expect it to
depend on such a resource.

I think I have my solution... I think this works. To recap: I am
using a static (global) reference to a class instance, which an
outside thread uses to access the class instance. The static
reference is updated by each instance of the class.

It would screw up if two instances were created, because they would
both change this static reference to point to themselves, but that
should never happen. But, just to be robust, maybe I should do that
singleton thing to catch for such errors.

Titan
 
In other words, what I have now works.

But, I should code a catch for mistaken double instances (which are
not supposed to happen). And to do that, I use singletons, right?

Titan
 
Back
Top