Hi
I have some questions about this code, http://code.doria.se/?c=18.
1. Will the Adapter class be thread-safe?
2. In the #region Way 1 I use lock(_lockobj) every time I go about and do
something, is this necessary?
3. If the answer in question 2 is no, when are one suppose to use lock()? Or
is it enough with what going on in Instance.
4. Anything else I need to know?
Thanks 8 2017
Hi Senna,
1. -> yes, at least in .Net (I beleive this will not be thread safe in
Java, at least before 1.5, but I am no Java expert). There are some other
easier ways to achieve what you are doing, for example just delare an
instance of the Adapter class when you define the variable i.e.
private static Adapter _instance = new Adapter();
since the instnace it static it is guaranteed to only get instantiated once
even across multiple threads, plus now you don't have the overhead of
acquiring the lock each time someone accesses the instance property (not that
it is really that much of an overhead, but if its not necessary no need to do
it :-) ).
2. You need to use the lock keyword every time you are trying to
access/modify a resource that is being shared. In your case I would say the
Foo1 set needs a lock because you might be inside one of your other methods
using the Foo1 variable and you don't want it being modified half way
through. I would lock just like you have apart from the Foo1 get which since
it is only one atomic operation I don't believe that you need to lock on that.
For a really good tutorial on Threading see: http://www.yoda.arachsys.com/csharp/threads/
Hope that helps
Mark Dawson http://www.markdawson.org
"Senna" wrote: Hi
I have some questions about this code, http://code.doria.se/?c=18.
1. Will the Adapter class be thread-safe?
2. In the #region Way 1 I use lock(_lockobj) every time I go about and do something, is this necessary?
3. If the answer in question 2 is no, when are one suppose to use lock()? Or is it enough with what going on in Instance.
4. Anything else I need to know?
Thanks
Hi Mark.
In the tutorial, great by the way, he says: "For "static locks" you should
declare a private static variable (and immediately instantiate a new object)
for the same reason - other classes can get a Type reference to your type
too! While it is unlikely that they would lock on your type, it's not
impossible - a private static variable keeps the lock invisible to other
classes. In both cases, make the variable read-only to stop yourself from
accidentally changing the value."
This is a little over my head, but...
If I use
private static Adapter _instance = new Adapter();
wouldn't that mean I lock on something that could be tampered with? Cause it
is the _instance that gets returned.
But if I use
private static object _lockObj = new object();
that object would only be used internally to lock() on.
And he says "immediatel y instantiate a new object" do that mean object like
= new object();
or do
= new Adapter();
actually go under that definition too.
He also recommends to set it as readonly.
private static readonly Adapter _instance = new Adapter();
Does that make any difference when using "new object();" or "new Adapter();".
Or should this be enough.
private static readonly Adapter _instance = new Adapter();
public static Adapter Instance
{
get { return _instance; }
}
/ Senna
"Mark R. Dawson" wrote: Hi Senna, 1. -> yes, at least in .Net (I beleive this will not be thread safe in Java, at least before 1.5, but I am no Java expert). There are some other easier ways to achieve what you are doing, for example just delare an instance of the Adapter class when you define the variable i.e.
private static Adapter _instance = new Adapter();
since the instnace it static it is guaranteed to only get instantiated once even across multiple threads, plus now you don't have the overhead of acquiring the lock each time someone accesses the instance property (not that it is really that much of an overhead, but if its not necessary no need to do it :-) ).
2. You need to use the lock keyword every time you are trying to access/modify a resource that is being shared. In your case I would say the Foo1 set needs a lock because you might be inside one of your other methods using the Foo1 variable and you don't want it being modified half way through. I would lock just like you have apart from the Foo1 get which since it is only one atomic operation I don't believe that you need to lock on that.
For a really good tutorial on Threading see: http://www.yoda.arachsys.com/csharp/threads/
Hope that helps Mark Dawson http://www.markdawson.org "Senna" wrote:
Hi
I have some questions about this code, http://code.doria.se/?c=18.
1. Will the Adapter class be thread-safe?
2. In the #region Way 1 I use lock(_lockobj) every time I go about and do something, is this necessary?
3. If the answer in question 2 is no, when are one suppose to use lock()? Or is it enough with what going on in Instance.
4. Anything else I need to know?
Thanks
Senna <Se***@discussi ons.microsoft.c om> wrote: In the tutorial, great by the way, he says: "For "static locks" you should declare a private static variable (and immediately instantiate a new object) for the same reason - other classes can get a Type reference to your type too! While it is unlikely that they would lock on your type, it's not impossible - a private static variable keeps the lock invisible to other classes. In both cases, make the variable read-only to stop yourself from accidentally changing the value."
This is a little over my head, but...
If I use private static Adapter _instance = new Adapter(); wouldn't that mean I lock on something that could be tampered with? Cause it is the _instance that gets returned.
Yes, that's a bad idea - someone else might lock on it.
But if I use private static object _lockObj = new object(); that object would only be used internally to lock() on.
Yes, that's the way to go.
And he says "immediatel y instantiate a new object" do that mean object like = new object(); or do = new Adapter(); actually go under that definition too.
He also recommends to set it as readonly. private static readonly Adapter _instance = new Adapter(); Does that make any difference when using "new object();" or "new Adapter();".
It makes no odds to whether you use Adapter or Object as your lock
type, but I'd recommend using object (and making it an object which is
used for no other purpose) for the reasons stated.
--
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
Ok, I will go with the object then.
One more question. The advise above was to use lock() when I should access
shared data. Does this include when I go to a database too, to do any CRUD
actions. I mean could muliple threads go in and use the same database
connection. Wonder this because the SqlMembership and Role Providers don't
use lock() for this.
"Jon Skeet [C# MVP]" wrote: Senna <Se***@discussi ons.microsoft.c om> wrote: In the tutorial, great by the way, he says: "For "static locks" you should declare a private static variable (and immediately instantiate a new object) for the same reason - other classes can get a Type reference to your type too! While it is unlikely that they would lock on your type, it's not impossible - a private static variable keeps the lock invisible to other classes. In both cases, make the variable read-only to stop yourself from accidentally changing the value."
This is a little over my head, but...
If I use private static Adapter _instance = new Adapter(); wouldn't that mean I lock on something that could be tampered with? Cause it is the _instance that gets returned.
Yes, that's a bad idea - someone else might lock on it.
But if I use private static object _lockObj = new object(); that object would only be used internally to lock() on.
Yes, that's the way to go.
And he says "immediatel y instantiate a new object" do that mean object like = new object(); or do = new Adapter(); actually go under that definition too.
He also recommends to set it as readonly. private static readonly Adapter _instance = new Adapter(); Does that make any difference when using "new object();" or "new Adapter();".
It makes no odds to whether you use Adapter or Object as your lock type, but I'd recommend using object (and making it an object which is used for no other purpose) for the reasons stated.
-- 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
Senna wrote: Ok, I will go with the object then.
One more question. The advise above was to use lock() when I should access shared data. Does this include when I go to a database too, to do any CRUD actions. I mean could muliple threads go in and use the same database connection. Wonder this because the SqlMembership and Role Providers don't use lock() for this.
Each database action should open the database connection and close it.
The connection pooling will work out what to do with the physical
connections. This way you should never end up with two different
threads sharing the same physical connection.
Wherever possible, write your code so that it doesn't *need* to be
thread-safe - many, many objects only really need to be used by a
single thread, or maybe a single thread at a time, and it makes life a
lot easier to work that way.
Jon
The obvious question that pops up, how do one know it doesn't *need* to be
thread-safe? Maybe a wide question to answer so do you know any articles
about it?
"Jon Skeet [C# MVP]" wrote: Senna wrote: Ok, I will go with the object then.
One more question. The advise above was to use lock() when I should access shared data. Does this include when I go to a database too, to do any CRUD actions. I mean could muliple threads go in and use the same database connection. Wonder this because the SqlMembership and Role Providers don't use lock() for this.
Each database action should open the database connection and close it. The connection pooling will work out what to do with the physical connections. This way you should never end up with two different threads sharing the same physical connection.
Wherever possible, write your code so that it doesn't *need* to be thread-safe - many, many objects only really need to be used by a single thread, or maybe a single thread at a time, and it makes life a lot easier to work that way.
Jon
Senna wrote: The obvious question that pops up, how do one know it doesn't *need* to be thread-safe? Maybe a wide question to answer so do you know any articles about it?
You advertise whether or not it *is* thread-safe, and adapt it
appropriately. I find that classes which aren't aware of being used by
multiple threads (i.e. they're not doing thready things themselves)
usually don't need to be thread-safe. It's a good starting point to
assume they don't need to be, then make them more thread-safe where
necessary.
(Making static members thread-safe is a good idea, however.)
Jon
Ok, I think I got it know. Finally. :)
Thanks for your time and knowledge.
/ Senna
"Jon Skeet [C# MVP]" wrote: Senna wrote: The obvious question that pops up, how do one know it doesn't *need* to be thread-safe? Maybe a wide question to answer so do you know any articles about it?
You advertise whether or not it *is* thread-safe, and adapt it appropriately. I find that classes which aren't aware of being used by multiple threads (i.e. they're not doing thready things themselves) usually don't need to be thread-safe. It's a good starting point to assume they don't need to be, then make them more thread-safe where necessary.
(Making static members thread-safe is a good idea, however.)
Jon
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: adeger |
last post by:
Having trouble with my first forays into threads. Basically, the
threads don't seem to be working in parallel (or you might say are
blocking). I've boiled my problems to the following short code block
and ensuing output. Seems like the output should be all interleaved
and of course it's not. Running Python 2.2 from ActiveState on
Windows XP (also doesn't work on Windows 2000).
Thanks in advance!
adeger
|
by: Gilles Leblanc |
last post by:
Hi I have started a small project with PyOpenGL. I am wondering what
are the options for a GUI. So far I checked PyUI but it has some
problems with 3d rendering outside the Windows platform.
I know of WxPython but I don't know if I can create a WxPython window,
use gl rendering code in it and then put widgets on top of that...
|
by: Ivan |
last post by:
Hi
I have following problem: I'm creating two threads who are performing some
tasks. When one thread finished I would like to restart her again (e.g. new
job). Following example demonstrates that. Problem is that when program is
started many threads are created (see output section), when only two should
be running at any time. Can you please help me to identify me where the
problem is?
Best regards
|
by: Matthew Groch |
last post by:
Hi all,
I've got a server that handles a relatively high number of concurrent
transactions (on the magnitude of 1000's per second). Client
applications establish socket connections with the server. Data is
sent and received over these connections using the asynchronous model.
The server is currently in beta testing. Sporadically over the course
of the day, I'll observe the thread count on the process (via perfmon)
start climbing....
|
by: Razzie |
last post by:
Hi all,
A question from someone on a website got me thinking about this, and I
wondered if anyone could explain this.
A System.Threading.Timer object is garbage collected if it has no references
to it. But what about threads? If I start a new thread that only does 1+1,
is it garbage collected after that? If so, do all threads get garbage
collected eventually that are 'done'? And if not, why not? Are there
references to the thread that...
| |
by: droopytoon |
last post by:
Hi,
I start a new thread (previous one was "thread timing") because I have
isolated my problem.
It has nothing to do with calling unmanaged C++ code (I removed it in a
test application).
I have a thread "_itTaskThread" running.
The application is listening on a TCP port.
It accepts 2 connection from a client.
I simulate a crash on the client side (using "Debug->StopDebugging").
|
by: mareal |
last post by:
I have noticed how the thread I created just stops running. I have added
several exceptions to the thread
System.Threading.SynchronizationLockException
System.Threading.ThreadAbortException
System.Threading.ThreadInterruptedException
System.Threading.ThreadStateException
to see if I could get more information about why the thread stops running
but that code is never executed. Any ideas on how I can debug this?
|
by: Bob Day |
last post by:
Using vs2003, vb.net
I start a thread, giving it a name before start. Code snippet:
'give each thread a unique name (for later identification)
Trunk_Thread.Name = "Trunk_0_Thread"
' allow only 1 thread per line
Trunk_Thread.ApartmentState = ApartmentState.STA
|
by: Charles Law |
last post by:
My first thought was to call
WorkerThread.Suspend
but the help cautions against this (for good reason) because the caller has
no control over where the thread actually stops, and it might have a lock
pending, for example.
I want to be able to stop a thread temporarily, and then optionally resume
it or stop it for good.
|
by: John Nagle |
last post by:
There's no way to set thread priorities within Python, is there?
We have some threads that go compute-bound, and would like to
reduce their priority slightly so the other operations, like
accessing the database and servicing queries, aren't slowed
as much.
John Nagle
|
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...
| |
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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,...
|
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...
|
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...
|
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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 we have to send another system
|
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |