473,505 Members | 13,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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?

Apr 9 '07 #1
12 3088
Typo:
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 *ensure* the outside thread is not calling the method when the class is
not instantiated.
Apr 9 '07 #2
OD
- 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.

--
OD___
www.e-naxos.com
Apr 9 '07 #3
Can you point me to more information on "the singleton pattern" and
singletons?

Titan

Apr 9 '07 #4
OD
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/UploadF...onPattern.aspx

--
OD___
www.e-naxos.com
Apr 9 '07 #5
titan nyquist <ti***********@gmail.comwrote:
Can you point me to more information on "the singleton pattern" and
singletons?
See http://pobox.com/~skeet/csharp/singleton.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 9 '07 #6
OD <OD <webmaster @ e-naxos dot com>wrote:

<snip>
C# example :

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

another one here :
http://www.c-sharpcorner.com/UploadF...ingletonPatter
n12052005063955AM/SingletonPattern.aspx
Unfortunately the latter page doesn't give a thread-safe version, and
has one version where you actually call a constructor - so you only get
a run-time effect rather than preventing the caller (at compile time)
from trying to create more than one instance in the first place.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 9 '07 #7
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

Apr 9 '07 #8
OD
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..

--
OD___
www.e-naxos.com
Apr 10 '07 #9
OD
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___
www.e-naxos.com
Apr 10 '07 #10
OD <OD <webmaster @ e-naxos dot com>wrote:
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...
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?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 10 '07 #11
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

Apr 10 '07 #12
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

Apr 10 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1551
by: Mike Frayn | last post by:
Hello there. I'm kinda new to Java, did some last year and have forgotten it all, but am experienced enough with C++. I have a problem here that I would imagine is solved very easily. I have...
17
2407
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next...
7
1644
by: Doug Thews | last post by:
I'm writing some sample threading code, and have already got many examples working that look a lot similar to the ones mentioned here. What I'm seeing is that most people put their method that...
3
3336
by: AdamM | last post by:
Hi all, When I run my VbScript, I get the error: "ActiveX component can't create object: 'getobject'. Error 800A01AD". Any ideas what I did wrong? Here's my VBScript: dim o set...
6
1895
by: Vladislav Kosev | last post by:
I have this strange problem now twice: I am writing this relatevely large web site on 2.0 and I made a static class, which I use for url encoding and deconding (for remapping purposes). This static...
6
2676
by: MattPKaiser | last post by:
I am trying to find a way to check if a computer on a network is "online" so that I can access a file on a share. In short I maintain a list of computers that have my service running (in the...
4
2127
by: Lilith | last post by:
This was easy in C++ (well, relatively.) Now I'm in the C# environment and everything I try doesn't work. I'm running a thread in which I have two accesses I need to components on a form. In...
1
5054
by: Tobias Maier | last post by:
Hi I want to start a C# ActiveX Exe with a parameter. Now, start a WebBrowser. Within Html/javascript I initiate my component und want to retrieve the parameter from the startet exe. I have...
1
4760
by: schnandr | last post by:
Hi, I have a user control which contains ListView. I copy all ListViewItems into a separate List<ListViewItemcalled unfilteredItems. I am using a BackgroundWorker to filter the ListView. When...
0
7213
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7098
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7471
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3187
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3176
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1526
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
406
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.