473,766 Members | 2,159 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threads, static variables

Hi,

the following .NET 1.1 C#-program does not terminate (opposed to what I
would expect):

--------
using System;
using System.Threadin g;

public class Test {

static int i = 0;

public static void Main(string [] args) {
new Thread(new ThreadStart(t1) ).Start();
new Thread(new ThreadStart(t2) ).Start();
}

static void t1() {
int j = 0;
while(i == 0) {
j++;
}
}

static void t2() {
i = 1;
}

}
--------

A slight variation of the above program makes the strange behavior more
explicit:

--------
using System;
using System.Threadin g;

public class Test {

static int i1 = 0;
static int i2 = 0;

public static void Main(string [] args) {
new Thread(new ThreadStart(t1) ).Start();
new Thread(new ThreadStart(t2) ).Start();
}

static void t1() {
int j = 0;
i1 = 1;
while(i2 == 0) {
j++;
if(j + 1 < j) break;
}
Console.WriteLi ne(j);
}

static void t2() {
i2 = 1;
Console.WriteLi ne("t2: i1={0}, i2={0}", i1, i2);
}

}
--------
Output:
--------
t2: i1=1, i2=1
2147483647
--------

That means thread t2 sets the static variable i2=1, but thread t1 seems
to be unaware of this change of i2.

Can anyone reproduce this behavior in his environment with the above
programs (don't change a single line, because even slight variations
result in a different behavior)?

And what I'm interested more: Can anyone explain why these programs
behave in this way? Is this a bug in .NET/C#?

Nov 17 '05 #1
6 2515
<kr*****@gmx.ne t> wrote:
the following .NET 1.1 C#-program does not terminate (opposed to what I
would expect):
<snip>
That means thread t2 sets the static variable i2=1, but thread t1 seems
to be unaware of this change of i2.
Yup.
Can anyone reproduce this behavior in his environment with the above
programs (don't change a single line, because even slight variations
result in a different behavior)?
It doesn't happen on my box, but that's a single processor box - are
you by any chance running it on a multi-processor box?
And what I'm interested more: Can anyone explain why these programs
behave in this way? Is this a bug in .NET/C#?


No, it's not a bug in .NET. It's the way the .NET memory model works.
See http://www.pobox.com/~skeet/csharp/t...latility.shtml

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

Willy.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<kr*****@gmx.ne t> wrote:
the following .NET 1.1 C#-program does not terminate (opposed to what I
would expect):


<snip>
That means thread t2 sets the static variable i2=1, but thread t1 seems
to be unaware of this change of i2.


Yup.
Can anyone reproduce this behavior in his environment with the above
programs (don't change a single line, because even slight variations
result in a different behavior)?


It doesn't happen on my box, but that's a single processor box - are
you by any chance running it on a multi-processor box?

The first sample won't terminate even on a single CPU when compiled with
full JIT optimization turned on (/o+ ), the static variable is register
allocated as opposed to heap allocated when not optimized (the default).
And what I'm interested more: Can anyone explain why these programs
behave in this way? Is this a bug in .NET/C#?


No, it's not a bug in .NET. It's the way the .NET memory model works.
See http://www.pobox.com/~skeet/csharp/t...latility.shtml

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

Nov 17 '05 #3
Hi,

Jon wrote:
It doesn't happen on my box, but that's a single processor box - are
you by any chance running it on a multi-processor box?
One Pentium-4 with hyperthreading turned off.
No, it's not a bug in .NET. It's the way the .NET memory model works.
See http://www.pobox.com/~skeet/csharp/t...latility.shtml
Thanks a lot for that URL. Declaring i and i2 as "volatile" helped!
Willy Denoyette [MVP] wrote: The first sample won't terminate even on a single CPU when compiled with
full JIT optimization turned on (/o+ ), the static variable is register
allocated as opposed to heap allocated when not optimized (the default).


"/o+" or "/o-" made no difference on my computer (first sample didn't
terminate in both cases).

Nov 17 '05 #4

<kr*****@gmx.ne t> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Hi,

Jon wrote:
It doesn't happen on my box, but that's a single processor box - are
you by any chance running it on a multi-processor box?


One Pentium-4 with hyperthreading turned off.
No, it's not a bug in .NET. It's the way the .NET memory model works.
See http://www.pobox.com/~skeet/csharp/t...latility.shtml


Thanks a lot for that URL. Declaring i and i2 as "volatile" helped!
Willy Denoyette [MVP] wrote:
The first sample won't terminate even on a single CPU when compiled with
full JIT optimization turned on (/o+ ), the static variable is register
allocated as opposed to heap allocated when not optimized (the default).


"/o+" or "/o-" made no difference on my computer (first sample didn't
terminate in both cases).


Try with /debug option on v1.1.4322, it should terminate. In this release
/o- is the default, and I guess it does register allocation per default
unless you have /debug specified.
Willy.
Nov 17 '05 #5
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
It doesn't happen on my box, but that's a single processor box - are
you by any chance running it on a multi-processor box?


The first sample won't terminate even on a single CPU when compiled with
full JIT optimization turned on (/o+ ), the static variable is register
allocated as opposed to heap allocated when not optimized (the default).


Ooh, indeed. That's great - a real sample I could include in my page,
which positively shows the dangers!

Cheers.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
> It doesn't happen on my box, but that's a single processor box - are
> you by any chance running it on a multi-processor box?
The first sample won't terminate even on a single CPU when compiled with
full JIT optimization turned on (/o+ ), the static variable is register
allocated as opposed to heap allocated when not optimized (the default).


Ooh, indeed. That's great - a real sample I could include in my page,
which positively shows the dangers!


Sure it is, note that I'm experimenting a bit with these settings, and there
seem to be a minor difference between v1.1 and v2 (the beta). In v2.0 /o- ,
keeps the static heap allocated, while /o+ does register allocation (in this
particular sample!). In V1.1 /o+ or /o- both use a register for the
variable. Moreover, that I notice this behavior is processor type dependent,
that is AMD Athlon64 and Intel P4 behave differently.
You see reasons enough to lock your shared state.
Cheers.

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

Nov 17 '05 #7

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

Similar topics

10
1930
by: Jeremie | last post by:
Hi, class A { <..> }; const A& GetA() { static A a;
6
2399
by: ouech | last post by:
hi, I'd like to know if i need mutexs to lock the use of member methods of a class instance shared between several threads via a pointer? if the method modify member variables, i know that mutexs are needed but the case that interrest me is when the method never modify a member variable. I really have no idea cause i don't know if the process duplicate the method in memory for each threads or if the local variables of
6
3205
by: m | last post by:
Hello, I have an application that processes thousands of files each day. The filenames and various related file information is retrieved, related filenames are associate and placed in a linked list within a single object, which is then placed on a stack(This cuts down thread creation and deletions roughly by a factor of 4). I create up to 12 threads, which then process a single object off of the stack. I use a loop with a boolean...
5
3830
by: Steve - DND | last post by:
I've seen many threads on Google about questions regarding stateless classes, and thread synchronization. However, either I am dense, or I have just not found the right thread, but I'm still not clear on how it all works. I understand that if I have a static member variable such as a collection, then I need to lock those operations as below, correct? public class StaticClass { private static HashTable m_Hash = new HashTable(); public...
7
1870
by: Mr. Mountain | last post by:
In the following code I simulate work being done on different threads by sleeping a couple methods for about 40 ms. However, some of these methods that should finish in about 40 -80 ms take as long as 2300 ms to complete. This is fairly rare, but the test code below will definitely show it. Somehow, I must not have my design right. The idea of this code is that I do two different types of processing ( 1-starting and 2-ending) based on...
2
1805
by: Oenone | last post by:
I'm upgrading a DLL from VB6 to VB.NET. The DLL gets called from an ASP.NET web application. In the VB6 code there is a module-level object which stores the context about what the user is doing during each page request. This object is initialised at the start of each request and populated with various data retrieved from the URL, and is then repeatedly queried throughout the rest of the page generation. Am I right in thinking that...
10
1761
by: Darian | last post by:
Is there a way to find all the thread names that are running in a project? For example, if I have 5 threads T1, T2, T3, T4, T5...and T2, T4, and T5 are running...I want to be able to know that T2, T4 and T5 are already running. Thanks, Darian
9
1410
by: jdlists | last post by:
I have inheirted some existing code, that i will explain in a moment, have needed to extend and ultimately should be able to run in threads. I've done a bunch of work with python but very little with threads and am looking for some pointers on how to implement, and if the lower level modules/objects need to be rewritten to use threading.local for all local variables. I have a module that communicates with a hardware device, which reads...
1
4143
by: chunghorng_lung | last post by:
Hi All, I have a question on the scope of variables for threads. The program has a main thread which creates a few worker threads. The main thread can access another class stored in another file, however, the worker threads can't. I got link errors for the code inside of the worker threads. The following contains code segments. Multi_Queue is a class and getXXX() is a public member function inside of Multi_Queue which is in...
0
9404
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,...
0
10168
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...
0
10009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
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
9838
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
8835
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...
0
6651
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
5279
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...
3
2806
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 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...

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.