473,473 Members | 1,970 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

if threads don't Sleep, synchronization will fail to occur ?!

OK, if you run this code below (Console app) you will find that threads will
not always behave in a synchronized fashion, even with a lock
statement, --unless you put a Sleep somewhere in the method passed to
ThreadStart.

Try it, and please prove me wrong.

********
using System;
using System.Threading;
namespace TestLockPrivate
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
innerClass2 a = new innerClass2();
a.startme();
innerClass2 b = new innerClass2();
b.startme();
innerClass2 c = new innerClass2();
c.startme();
}

public class innerClass1 {
private object alock = new object();
private static string str = "";
public void foo() {
lock(alock) {
str = Thread.CurrentThread.GetHashCode().ToString();
if (str !=
Thread.CurrentThread.GetHashCode().ToString()) {
Console.WriteLine("str = " + str + "
Thread.CurrentThread.GetHashCode().ToString() = " +
Thread.CurrentThread.GetHashCode().ToString());
}
}
}
}

public class innerClass2 {
public Thread t = null;
public void startme() {
t = new Thread(new ThreadStart(threadMain));
t.Start();
}
public void threadMain() {
while (true) {
innerClass1 l = new innerClass1();
l.foo();
}
}
}
}
}
Nov 15 '05 #1
2 1676

You are right! I added the static modifier to alock and now it is
synchronized.

But, can you please explain 3) below. I don't understand.
"Willy Denoyette [MVP]" <wi*************@skynet.be> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
pokémon wrote:
|| OK, if you run this code below (Console app) you will find that
|| threads will not always behave in a synchronized fashion, even with
|| a lock
|| statement, --unless you put a Sleep somewhere in the method passed to
|| ThreadStart.
||
|| Try it, and please prove me wrong.
||
|| ********
|| using System;
|| using System.Threading;
|| namespace TestLockPrivate
|| {
|| class Class1
|| {
|| [STAThread]
|| static void Main(string[] args)
|| {
|| innerClass2 a = new innerClass2();
|| a.startme();
|| innerClass2 b = new innerClass2();
|| b.startme();
|| innerClass2 c = new innerClass2();
|| c.startme();
|| }
||
|| public class innerClass1 {
|| private object alock = new object();
|| private static string str = "";
|| public void foo() {
|| lock(alock) {
|| str =
|| Thread.CurrentThread.GetHashCode().ToString();
|| if (str !=
|| Thread.CurrentThread.GetHashCode().ToString()) {
|| Console.WriteLine("str = " + str + "
|| Thread.CurrentThread.GetHashCode().ToString() = " +
|| Thread.CurrentThread.GetHashCode().ToString());
|| }
|| }
|| }
|| }
||
|| public class innerClass2 {
|| public Thread t = null;
|| public void startme() {
|| t = new Thread(new ThreadStart(threadMain));
|| t.Start();
|| }
|| public void threadMain() {
|| while (true) {
|| innerClass1 l = new innerClass1();
|| l.foo();
|| }
|| }
|| }
|| }
|| }

Well, you are wrong :-).
1. Each thread creates an instance of innerClass1 and foo() puts a lock on the object refered to by alock, but as this object is not shared every thread is free to enter foo().
2. Otherwise, str is a shared object reference (static) and not protected by a lock so each thread running foo() is free to toy with str.....
3. Now if you would synchronize access to str, running foo() in such a closed loop allmost prevents other threads to run at the end of the running threads quota.

Willy.

Nov 15 '05 #2
Thanks for the explanation. It is very interesting to get such a low-level
understanding of what's going on in the processor. BTW, is it a bad thing
for the threads to run much longer then their quantum?

"Willy Denoyette [MVP]" <wi*************@skynet.be> wrote in message
news:%2******************@TK2MSFTNGP12.phx.gbl...
pokémon wrote:
|| You are right! I added the static modifier to alock and now it is
|| synchronized.
||
|| But, can you please explain 3) below. I don't understand.
||
||
|| "Willy Denoyette [MVP]" <wi*************@skynet.be> wrote in message
|| news:%2****************@tk2msftngp13.phx.gbl...
||| 3. Now if you would synchronize access to str, running foo() in
||| such a
|| closed loop allmost prevents other threads to run at the end
||| of the running threads quota.
|||
||| Willy.

Each thread in the Windows system is allowed to run for an amount of time, called a quantum (quantum's can vary per thread and OS versions), before Windows interrupts the thread to see whether another thread (with higher or equal priority) is ready to run. Now if you take a look at your code, you have 3 runable threads (I don't consider the other threads in the process). While one thread is running the others are ready to run, but the running thread will run a large amount of it's quantum while holding a shared lock (running foo()) as such preventing the other two threads to run when scheduled (at the end of the running threads quantum) when the lock is still held (during foo()). The net result is that each thread will run for a much longer time than it's quantum (seconds i.s.o milliseconds).

Willy.

Nov 15 '05 #3

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

Similar topics

8
by: andrewpalumbo | last post by:
I'm trying to write some code which will split up a vector into two halves and run a method on the objects in the vector using two seperate threads. I was hoping to see a near linear speedup on an...
5
by: Michele Simionato | last post by:
I am getting a strange error with this script: $ cat doctest-threads.py """ >>> import time, threading >>> def example(): .... thread.out = .... while thread.running: .... ...
6
by: sathyashrayan | last post by:
Following are the selected thread from the date:30-jan-2005 to 31-jan-2005. I did not use any name because of the subject is important. You can get the original thread by typing the subject...
7
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...
10
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes,...
7
by: David Rushby | last post by:
Consider the following program (underscores are used to force indentation): ------------------------------------------------ import atexit, threading, time def atExitFunc(): ____print...
12
by: Dave | last post by:
Hi all, I have an application which has some worker threads which often have to stop and wait for some further information from other threads. These pauses will often take a long time (a couple...
4
by: tdahsu | last post by:
All, I'd appreciate any help. I've got a list of files in a directory, and I'd like to iterate through that list and process each one. Rather than do that serially, I was thinking I should...
23
by: =?GB2312?B?0rvK18qr?= | last post by:
Hi all, Recently I had a new coworker. There is some dispute between us. The last company he worked for has a special networking programming model. They split the business logic into...
0
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,...
0
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,...
1
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...
0
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...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
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...

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.