473,780 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ 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.Threadin g;
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.CurrentT hread.GetHashCo de().ToString() ;
if (str !=
Thread.CurrentT hread.GetHashCo de().ToString() ) {
Console.WriteLi ne("str = " + str + "
Thread.CurrentT hread.GetHashCo de().ToString() = " +
Thread.CurrentT hread.GetHashCo de().ToString() );
}
}
}
}

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

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******** ********@tk2msf tngp13.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.Threadin g;
|| 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.CurrentT hread.GetHashCo de().ToString() ;
|| if (str !=
|| Thread.CurrentT hread.GetHashCo de().ToString() ) {
|| Console.WriteLi ne("str = " + str + "
|| Thread.CurrentT hread.GetHashCo de().ToString() = " +
|| Thread.CurrentT hread.GetHashCo de().ToString() );
|| }
|| }
|| }
|| }
||
|| public class innerClass2 {
|| public Thread t = null;
|| public void startme() {
|| t = new Thread(new ThreadStart(thr eadMain));
|| 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******** **********@TK2M SFTNGP12.phx.gb l...
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******** ********@tk2msf tngp13.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
2305
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 SMP machine, but I'm finding that the code below takes almost exactly the same amount of time as when I iterate through the vector, and don't use any threads at all (using only one processor). I'm running this on a Dual Athlon machine under...
5
1803
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: .... time.sleep(.01) .... thread.out.append(".")
6
2138
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 "string" in google comp.lang.c archives.Hope this helps.Hope I am not bothering any one. am I? =================================Start=========================== subject: Return to Start of Line? Question: I'd like printf, the next printf, to return...
7
1872
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...
10
1682
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, OS execute (All have same priority) Thread#1 may be other threads, Thread#2 may be other threads, Thread#3 may be other threads,
7
6077
by: David Rushby | last post by:
Consider the following program (underscores are used to force indentation): ------------------------------------------------ import atexit, threading, time def atExitFunc(): ____print 'atExitFunc called.' atexit.register(atExitFunc)
12
2328
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 of minutes) and I want the thread to be able to begin work ASAP once the new information arrives so Thread.Sleep isn't the best solution. In .NET 1.1 I used .Suspend and .Resume to handle these pauses but in .NET 2.0 these methods are no longer...
4
2258
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 start five threads and process five files at a time. Is this a good idea? I picked the number five at random... I was thinking that I might check the number of processors and start a multiple of that, but then I remembered KISS and it seemed that...
23
4294
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 different modules, and have a dedicated thread for the each module. Modules exchanged info through a in-memory message queue. In my opinion, such a model means very complicated asynchronous
0
9636
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, 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...
0
9474
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
10306
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...
1
10075
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
8961
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...
1
7485
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 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...
0
6727
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
5373
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...
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.