473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Threadsafe value types

If a value type is immutable, I guess it's threadsafe to read it? But not
threadsafe to assign a new value to it (can any value type be truely
immutable? Isn't assigning a totally new value to it, like doing an
modification, when no references are involved? I don't know enough about
CLR)

At the moment the whole:

lock(anobject)
{
threadsafevar = new something(1,2,3,4,5); // is this needed for both value
and ref types?
}

Is fine, but it would be really good be able to *require* that a particular
variable was locked before access.

Thanks,

John
Nov 16 '05 #1
9 3152
I am not sure I know what you mean by immutable in this context. Strings are
immutable by virtue of the fact that if you try to assign to a string a new
string is created. This means a new reference is generated. Value types like
int etc. can be made readonly and can't be assigned to once initialized.

As far as I know there is absolutely no way to force a programmer to use
lock. You should also be aware that the volatile keyword should be used
with fields used with multi-threaded applications to prevent compiler
optimizations that cause caching and hence problems regardless of the use of
the lock. If something is accessed in more than one thread it make no
difference if it is a value or reference type.

Thomas P. Skinner [MVP]

"John" <js************@ecclesdeletethiscollege.ac.uk> wrote in message
news:uE****************@TK2MSFTNGP12.phx.gbl...
If a value type is immutable, I guess it's threadsafe to read it? But not
threadsafe to assign a new value to it (can any value type be truely
immutable? Isn't assigning a totally new value to it, like doing an
modification, when no references are involved? I don't know enough about
CLR)

At the moment the whole:

lock(anobject)
{
threadsafevar = new something(1,2,3,4,5); // is this needed for both value
and ref types?
}

Is fine, but it would be really good be able to *require* that a
particular variable was locked before access.

Thanks,

John

Nov 16 '05 #2
Hi Thomas,

There seem to me many types I can't make volatile.. including any structs
I've made, and DateTimes!

I thought lock() removed the need for 'volatile'?

By immutable value types I meant ones like DateTime, where you can't alter
fields / properties, except by creating a new instance. This seems to be
seen as 'a good thing' by the C# boffins at Microsoft. That whiteboard
lecture on MSDN TV certainly indicated it was (I need to get out more).

However, with my limited understanding of CLR, I would have thought that:

DateTime a = new DateTime(1970,1,1);
....
a = new DateTime(1971,1,1);

is actually breaking the immutability of 'a'. It's a value type, so are we
effectively changing it by doing something like 'year = 1971'? Or would the
old 'a' still exist somewhere until it's GCed?
"Thomas P. Skinner [MVP]" <to*@bu.edu> wrote in message
news:u2**************@TK2MSFTNGP15.phx.gbl...
I am not sure I know what you mean by immutable in this context. Strings
are immutable by virtue of the fact that if you try to assign to a string a
new string is created. This means a new reference is generated. Value types
like int etc. can be made readonly and can't be assigned to once
initialized.

As far as I know there is absolutely no way to force a programmer to use
lock. You should also be aware that the volatile keyword should be used
with fields used with multi-threaded applications to prevent compiler
optimizations that cause caching and hence problems regardless of the use
of the lock. If something is accessed in more than one thread it make no
difference if it is a value or reference type.

Thomas P. Skinner [MVP]

"John" <js************@ecclesdeletethiscollege.ac.uk> wrote in message
news:uE****************@TK2MSFTNGP12.phx.gbl...
If a value type is immutable, I guess it's threadsafe to read it? But not
threadsafe to assign a new value to it (can any value type be truely
immutable? Isn't assigning a totally new value to it, like doing an
modification, when no references are involved? I don't know enough about
CLR)

At the moment the whole:

lock(anobject)
{
threadsafevar = new something(1,2,3,4,5); // is this needed for both
value and ref types?
}

Is fine, but it would be really good be able to *require* that a
particular variable was locked before access.

Thanks,

John


Nov 16 '05 #3
You are correct. A struct can't be made volatile. Any reference type can as
well as various ints, floats, char and enum. They must be fields however.

As to your example, Just make it readonly. Consider this:

int i=1;
int i=2;

i is not immutable, but the 1 and the 2 are. Same thing with DateTime.

Thomas P. Skinner [MVP]

"John" <js************@ecclesdeletethiscollege.ac.uk> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hi Thomas,

There seem to me many types I can't make volatile.. including any structs
I've made, and DateTimes!

I thought lock() removed the need for 'volatile'?

By immutable value types I meant ones like DateTime, where you can't alter
fields / properties, except by creating a new instance. This seems to be
seen as 'a good thing' by the C# boffins at Microsoft. That whiteboard
lecture on MSDN TV certainly indicated it was (I need to get out more).

However, with my limited understanding of CLR, I would have thought that:

DateTime a = new DateTime(1970,1,1);
...
a = new DateTime(1971,1,1);

is actually breaking the immutability of 'a'. It's a value type, so are we
effectively changing it by doing something like 'year = 1971'? Or would
the old 'a' still exist somewhere until it's GCed?
"Thomas P. Skinner [MVP]" <to*@bu.edu> wrote in message
news:u2**************@TK2MSFTNGP15.phx.gbl...
I am not sure I know what you mean by immutable in this context. Strings
are immutable by virtue of the fact that if you try to assign to a string
a new string is created. This means a new reference is generated. Value
types like int etc. can be made readonly and can't be assigned to once
initialized.

As far as I know there is absolutely no way to force a programmer to use
lock. You should also be aware that the volatile keyword should be used
with fields used with multi-threaded applications to prevent compiler
optimizations that cause caching and hence problems regardless of the use
of the lock. If something is accessed in more than one thread it make no
difference if it is a value or reference type.

Thomas P. Skinner [MVP]

"John" <js************@ecclesdeletethiscollege.ac.uk> wrote in message
news:uE****************@TK2MSFTNGP12.phx.gbl...
If a value type is immutable, I guess it's threadsafe to read it? But
not threadsafe to assign a new value to it (can any value type be truely
immutable? Isn't assigning a totally new value to it, like doing an
modification, when no references are involved? I don't know enough about
CLR)

At the moment the whole:

lock(anobject)
{
threadsafevar = new something(1,2,3,4,5); // is this needed for both
value and ref types?
}

Is fine, but it would be really good be able to *require* that a
particular variable was locked before access.

Thanks,

John



Nov 16 '05 #4
John... As Thomas suggested if you declare the variable readonly the
compiler appears to block setters in the structure.

Regards,
Jeff
If a value type is immutable, I guess it's threadsafe to read it? But

not threadsafe to assign a new value to it(can any value type be truely
immutable?<

====== code =============

using System;

namespace TestStruct
{
public struct MutableS
{
private int i;
public int I
{
get {return i;}
set {this.i= value;}
}
public MutableS(int i)
{
this.i=i;
}
}

/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static readonly MutableS ro_sm= new MutableS(1);
static MutableS sm= new MutableS(2);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
//Class1.ro_sm.I= 3; // will not compile!
Class1.sm.I= 4;
}
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #5
Thanks for the help guys.

So is there no added value in having a create-only value type like DateTime,
that doesn't give write access to it's fields / properties?

MSDN gives the impression struct's that allow field modification are bad -
but I can't see why if these two are equivelent:

// editable struct instance
DateTime a = new DateTime(1970,1,1);
a.ChangeDay(2); // a fictional method I made up to alter the
DateTime struct!

....and...

// new struct instance
DateTime a = new DateTime(1970,1,1);
a = new DateTime(1970,1,2);

Would these be functional equivelent?

John

"Jeff Louie" <je********@yahoo.com> wrote in message
news:O3**************@TK2MSFTNGP14.phx.gbl...
John... As Thomas suggested if you declare the variable readonly the
compiler appears to block setters in the structure.

Regards,
Jeff
If a value type is immutable, I guess it's threadsafe to read it? But

not threadsafe to assign a new value to it(can any value type be truely
immutable?<

====== code =============

using System;

namespace TestStruct
{
public struct MutableS
{
private int i;
public int I
{
get {return i;}
set {this.i= value;}
}
public MutableS(int i)
{
this.i=i;
}
}

/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static readonly MutableS ro_sm= new MutableS(1);
static MutableS sm= new MutableS(2);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
//Class1.ro_sm.I= 3; // will not compile!
Class1.sm.I= 4;
}
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #6
Thomas P. Skinner [MVP] <to*@bu.edu> wrote:

<snip>
You should also be aware that the volatile keyword should be used
with fields used with multi-threaded applications to prevent compiler
optimizations that cause caching and hence problems regardless of the use of
the lock.


That's not true. Acquiring a lock involves a volatile read, and
releasing it involves a volatile write, so volatility isn't required if
you're using locks appropriately.

See http://www.pobox.com/~skeet/csharp/t...latility.shtml

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
This is a good point but the use of a lock does not actually eliminate the
compiler or runtime from optimizations on fields not marked as volatile.
Sure, if all accesses are inside the locked block then there would be no
problems in practice. But having knowledge of the existence of the volatile
modifier is certainly worthwhile.

Thomas P. Skinner [MVP]
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Thomas P. Skinner [MVP] <to*@bu.edu> wrote:

<snip>
You should also be aware that the volatile keyword should be used
with fields used with multi-threaded applications to prevent compiler
optimizations that cause caching and hence problems regardless of the use
of
the lock.


That's not true. Acquiring a lock involves a volatile read, and
releasing it involves a volatile write, so volatility isn't required if
you're using locks appropriately.

See http://www.pobox.com/~skeet/csharp/t...latility.shtml

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #8
John....>So is there no added value in having a create-only value type
like
DateTime, that doesn't give write access to it's fields / properties?<

A very good question. Most would not argue about the advantages of using
immutable classes. The advantages for immutable structures are less
obvious
since they use value semantics and provide automatic "defensive copies."
Still
immutable structures are going to be simple, reliable and useful for
building
complex objects.

Let me turn the question around. Since most structures are simple small
constructs that are easily passed and copied using value semantics, why
not
simplify your life/code and write only immutable structures? A typical
method
might take an "instance" of a value type and return a different
"instance" of
the same value type or just it may just read the value. So a typical
method
would not need access to any setters outside of initialization which can
be
done in the constructor.

So immutable structures are simpler and more reliable than mutable
structures, but may be harder to initialize since you must know the
proper
order to pass the arguments to the constructor as opposed to using named
setters.
// editable struct instance

DateTime a = new DateTime(1970,1,1);
a.ChangeDay(2); // a fictional method I made up to alter the
DateTime struct!

....and...

// new struct instance
DateTime a = new DateTime(1970,1,1);
a = new DateTime(1970,1,2);

Would these be functional equivelent?<

In the sense that the containing object's state is mutated either way,
yes. So
to _build_ a immutable class (as opposed to using a immutable class) "a"
should be private. You can do anything you want within the class as long
as
no method makes an externally visible change in the objects state and
the
object does not violate an invariant for which it is responsible.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #9
Thomas P. Skinner [MVP] <to*@bu.edu> wrote:
This is a good point but the use of a lock does not actually eliminate the
compiler or runtime from optimizations on fields not marked as volatile.
Not outside the lock, no. But then if you're using locks in some
places, you almost certainly shouldn't be accessing the variables
without acquiring a lock in *all* places anyway. There's no need to use
the volatile modifier to achieve thread safety, contrary to the
statement in your earlier post.
Sure, if all accesses are inside the locked block then there would be no
problems in practice.
And none in theory either. If we were only talking about "in practice"
scenarios, there's an awful lot you can get away with which I wouldn't
recommend.
But having knowledge of the existence of the volatile
modifier is certainly worthwhile.


Undoubtedly, although I prefer not to use volatile fields myself, using
locks instead.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

0
by: Jason Morehouse | last post by:
Hello, Just wondering if anyone is using the apache worker module with php? I've complied php5 with zend threadsafe support, and apache2 with the MPM worker module on a Linux box. Everything...
11
by: Jeff Schwab | last post by:
Is it OK for multiple threads to use the same PrintWriter concurrently?
0
by: Cole Tuininga | last post by:
Quick question for y'all - is a dict's setdefault call threadsafe? In other words, if I have code like the following: tmp = someObj() result = dictname.setdefault( key, tmp ) is it...
0
by: Stephanie Stowe | last post by:
Hi. I have been posting like a looney on an issue I am working on. I will reiterate the background since you all do not want to remember my issues! I have an ASP app (biggish). We are creating...
5
by: martin | last post by:
Hi, Is there any best practice guidelines or examples for threadsafe logging? I have to write an auditlogging class for a website. The auditlog will be stored in files on the local filesystem. A...
2
by: David | last post by:
I have a static method in the dll that looks like this public static int myStaticFunction(int input){ } My question is, should I use a mutex inside the function to ensure that the function is...
3
by: Diffident | last post by:
Hello All, Following is a static method. Can you please tell me if this is threadsafe...why? If it is not threadsafe...why? Thank you. public static string...
2
by: Macca | last post by:
Hi, I need a data structure such as an Array/ArrayList/Generic List to hold multiple instances of a user derfined class. This array will be accessed across multiple threads. However I dont...
5
by: Spam Catcher | last post by:
Hi all, I'm accessing a synchronized Streamwriter from potentially several threads to do some logging. Is the Flush command threadsafe too? Should I single thread the Flush command or will the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.