473,749 Members | 2,350 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 3116
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.co m>
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
n12052005063955 AM/SingletonPatter n.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.co m>
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

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

Similar topics

1
1561
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 a class that contains a main function: // pseudo-code: please don't condemn the syntax or // missing keywords
17
2439
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 = gen.next() finally:
7
1653
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 will be run as a thread inside the overall Form's class, which is OK for examples, but not really what you'd see in real life. So, I decided to write a class (called BusinessOperation) and have properties & methods in it. Then, I have 1 method in...
3
3345
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 o=getobject(,"ConsoleApplication2.Program") msgbox o.TestString
6
1914
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 class needs the session context to encode a url (because I stored the current language there), so I made a static field of type HttpContext, which I refresh every reqest by assigning the current context. Now, every now and then I get this...
6
2687
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 client application) and in my client program I allow the user to change the computer that they are accessing. If a computer that is on the list becomes unplugged and I try to access a file with a FileStream the filestream creation takes 8-10...
4
2139
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 one instance it's to simply check the text of a button as an indicator of whether I've got a request to end the thread. This is a read-only situation so I don't have to worry about synchronization. The other is a need to write status information...
1
5059
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 done this in VB6 with new ActiveXObject("name") and all works correct. Using C# or Vb.net it works different:
1
4799
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 I access this list in the DoWork Handler I am getting an InvalidOperationException that the List was not created by this thread. Is there a way to solve this problem?
0
8996
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9333
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6800
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.