Microsoft Developer Network >
Página Inicial dos Fóruns
>
.NET Base Class Library
>
Accessing a global variable from two separate threads
Accessing a global variable from two separate threads
I have a program that needs to access a global variable of type double from two different threads. Since it is just type double, do I still have to lock that code? I know this may not be the best programming practice, but for right now, this is what I am stuck with.
Thanks!!
Respostas
- Yes, using a lock would be wise.
Mark the best replies as answers. "Fooling computers since 1971."- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
- Reads of 4 bytes that are aligned are atomic. Reads of unaligned bytes are not atomic. And reads of 8 bytes (doubles) are not atomic. So use a lock .
You are not stuck with anything...we can help you find options. It's not that hard either.
class foo {
private double n = 0.0;
public void AddOne() {
lock(this) {
n += 1.0;
}
}
public double Get() {
lock(this) {
return n;
}
}
}
If you feel your lock is inefficient, then let's discuss your algorithm. Maybe you could offer a bit more of the details of your program and what you're trying to accomplish.- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
- Yes, use a lock. But as you mentioned its a global (so static) variable, use it this way..
class yourClass
{
yourFunction()
{
lock(typeof(ClassContainingStatic)) // or any class for that matter, so it will be a global lock
{
your code;
}
}
}
Hope that helps..- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
Todas as Respostas
- Yes, using a lock would be wise.
Mark the best replies as answers. "Fooling computers since 1971."- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
- Reads of 4 bytes that are aligned are atomic. Reads of unaligned bytes are not atomic. And reads of 8 bytes (doubles) are not atomic. So use a lock .
You are not stuck with anything...we can help you find options. It's not that hard either.
class foo {
private double n = 0.0;
public void AddOne() {
lock(this) {
n += 1.0;
}
}
public double Get() {
lock(this) {
return n;
}
}
}
If you feel your lock is inefficient, then let's discuss your algorithm. Maybe you could offer a bit more of the details of your program and what you're trying to accomplish.- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
- Yes, use a lock. But as you mentioned its a global (so static) variable, use it this way..
class yourClass
{
yourFunction()
{
lock(typeof(ClassContainingStatic)) // or any class for that matter, so it will be a global lock
{
your code;
}
}
}
Hope that helps..- Marcado como Respostatcmo44 quarta-feira, 4 de novembro de 2009 13:36
- The lock should be sufficient. If I run into more problems, I'll give a holler. Thanks for the input!!!

