473,394 Members | 1,932 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,394 software developers and data experts.

Thread synchronization problem

Hi

I have following problem: I'm creating two threads who are performing some
tasks. When one thread finished I would like to restart her again (e.g. new
job). Following example demonstrates that. Problem is that when program is
started many threads are created (see output section), when only two should
be running at any time. Can you please help me to identify me where the
problem is?

Best regards
Ivan
Source
================

private void btnStartThreads_Click(object sender, System.EventArgs e)
{
JobAgent ag1 = new JobAgent ();
JobAgent ag2 = new JobAgent ();
while (true)
{
if (ag1.IsRunning == false)
{
Thread t1 = new Thread (new ThreadStart (ag1.Run));
t1.Start ();
}
if (ag2.IsRunning == false)
{
Thread t2 = new Thread (new ThreadStart (ag2.Run));
t2.Start ();
}

}
}
}

public class JobAgent
{
protected ThreadStatus status = new ThreadStatus ();

public void Run ()
{
IsRunning = true;
Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " started");
Thread.Sleep (5000);
Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " finished");
IsRunning = false;
}

public bool IsRunning
{
get
{
lock (status)
{
return status.isRunning;
}
}
set
{
lock (status)
{
status.isRunning = value;
}
}
}

}

public class ThreadStatus
{
public bool isRunning = false;
}
}
Output
================

Thread num. 10 started
Thread num. 13 started
Thread num. 14 started
Thread num. 15 started
Thread num. 16 started
Thread num. 17 started
Thread num. 18 started
Thread num. 58 started
Thread num. 11 started
Thread num. 12 started
Thread num. 19 started
Thread num. 20 started
Thread num. 21 started
Thread num. 22 started
Thread num. 23 started
Thread num. 24 started
Thread num. 57 started
Thread num. 25 started
Thread num. 26 started
Thread num. 27 started
Thread num. 28 started
Thread num. 10 finished
The thread '<No Name>' (0x1544) has exited with code 0 (0x0).
Thread num. 13 finished
The thread '<No Name>' (0x12dc) has exited with code 0 (0x0).
Thread num. 14 finished
The thread '<No Name>' (0xabc) has exited with code 0 (0x0).
Thread num. 15 finished
The thread '<No Name>' (0x930) has exited with code 0 (0x0).
Thread num. 17 finished
Thread num. 18 finished
The thread '<No Name>' (0xd7c) has exited with code 0 (0x0).
Thread num. 16 finished
The thread '<No Name>' (0xda8) has exited with code 0 (0x0).
Thread num. 29 started
The thread '<No Name>' (0x1590) has exited with code 0 (0x0).
Nov 16 '05 #1
7 2672
Ivan <no******@today.com> wrote:
I have following problem: I'm creating two threads who are performing some
tasks. When one thread finished I would like to restart her again (e.g. new
job). Following example demonstrates that. Problem is that when program is
started many threads are created (see output section), when only two should
be running at any time. Can you please help me to identify me where the
problem is?


Well for one thing, there's nothing to say that just because you've
called Start on the thread, the first line of the method you've
specified will have run.

I would suggest using events and the like to signal when a job has
finished, rather than relying on a status flag like this.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
I thought about events, but how can I achieve that only one thread per time
can fire that event (if two threads end at same time and try to fire e.g.
ThreadFinished event at the same time)?

Ivan

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
Ivan <no******@today.com> wrote:
I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the
problem is?


Well for one thing, there's nothing to say that just because you've
called Start on the thread, the first line of the method you've
specified will have run.

I would suggest using events and the like to signal when a job has
finished, rather than relying on a status flag like this.

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

Nov 16 '05 #3
Ivan <no******@today.com> wrote:
I thought about events, but how can I achieve that only one thread per time
can fire that event (if two threads end at same time and try to fire e.g.
ThreadFinished event at the same time)?


Well, you can use locking to make sure that only one of the threads is
executing the event handler at any one time...

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

Even without events your code is ok. The problem is the moment you set the
IsRunning flag.
You cannot guarantee that the loop in the main thread wont run several times
before the first line of the worker thread set the falg. And you will endup
with many threads started. That's what actually happens.

to make your code work set the falg right before starting the thread

The loop should look like this

while (true)
{
if (ag1.IsRunning == false)
{
Thread t1 = new Thread (new ThreadStart (ag1.Run));
ag1.IsRunning = true;
t1.Start ();
}
if (ag2.IsRunning == false)
{
Thread t2 = new Thread (new ThreadStart (ag2.Run));
ag2.IsRunning = true;
t2.Start ();
}

}

remove setting the flag to true at the beginning of the Run method. Leave
setting the flag to false, though.

Run method should look like this.

public void Run ()
{
Console.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " started");
Thread.Sleep (5000);
Console.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " finished");
IsRunning = false;
}

Now ot will work correctly. However the main thread doesn't need to know
anything about setting that flag, as a matter of fact it doesn't need to
know that there are threads at all. So, my suggestion is to move the code
for starting the thread and setting the flag in the JobAgen class. The main
thread in this case will look as follows
while (true)
{
if (!ag1.IsBusy)
{
ag1.DoJob()
}
if (!ag2.IsBusy)
{
ag2.DoJob();
}

}

--
HTH
Stoitcho Goutsev (100) [C# MVP]
"Ivan" <no******@today.com> wrote in message
news:cc**********@fegnews.vip.hr...
I thought about events, but how can I achieve that only one thread per time can fire that event (if two threads end at same time and try to fire e.g.
ThreadFinished event at the same time)?

Ivan

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
Ivan <no******@today.com> wrote:
I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g.
new
job). Following example demonstrates that. Problem is that when
program
is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where

the problem is?


Well for one thing, there's nothing to say that just because you've
called Start on the thread, the first line of the method you've
specified will have run.

I would suggest using events and the like to signal when a job has
finished, rather than relying on a status flag like this.

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


Nov 16 '05 #5
Thx. for help. I think that there is similar problem when thread ends: it
sets the flag that is not busy (last statement in thread), but thread will
be actualy terminated few milliseconds after. Is there some better way to
achieve same functionality like in example and to get complete
synchronization?

Ivan
"Stoitcho Goutsev (100) [C# MVP]" <10*@100.com> wrote in message
news:uF**************@TK2MSFTNGP10.phx.gbl...
Hi Ivan,

Even without events your code is ok. The problem is the moment you set the
IsRunning flag.
You cannot guarantee that the loop in the main thread wont run several times before the first line of the worker thread set the falg. And you will endup with many threads started. That's what actually happens.

to make your code work set the falg right before starting the thread

The loop should look like this

while (true)
{
if (ag1.IsRunning == false)
{
Thread t1 = new Thread (new ThreadStart (ag1.Run));
ag1.IsRunning = true;
t1.Start ();
}
if (ag2.IsRunning == false)
{
Thread t2 = new Thread (new ThreadStart (ag2.Run));
ag2.IsRunning = true;
t2.Start ();
}

}

remove setting the flag to true at the beginning of the Run method. Leave
setting the flag to false, though.

Run method should look like this.

public void Run ()
{
Console.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " started");
Thread.Sleep (5000);
Console.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " finished");
IsRunning = false;
}

Now ot will work correctly. However the main thread doesn't need to know
anything about setting that flag, as a matter of fact it doesn't need to
know that there are threads at all. So, my suggestion is to move the code
for starting the thread and setting the flag in the JobAgen class. The main thread in this case will look as follows
while (true)
{
if (!ag1.IsBusy)
{
ag1.DoJob()
}
if (!ag2.IsBusy)
{
ag2.DoJob();
}

}

--
HTH
Stoitcho Goutsev (100) [C# MVP]
"Ivan" <no******@today.com> wrote in message
news:cc**********@fegnews.vip.hr...
I thought about events, but how can I achieve that only one thread per

time
can fire that event (if two threads end at same time and try to fire e.g.
ThreadFinished event at the same time)?

Ivan

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
Ivan <no******@today.com> wrote:
> I have following problem: I'm creating two threads who are
performing some
> tasks. When one thread finished I would like to restart her again

(e.g.
new
> job). Following example demonstrates that. Problem is that when

program
is
> started many threads are created (see output section), when only two

should
> be running at any time. Can you please help me to identify me where

the > problem is?

Well for one thing, there's nothing to say that just because you've
called Start on the thread, the first line of the method you've
specified will have run.

I would suggest using events and the like to signal when a job has
finished, rather than relying on a status flag like this.

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



Nov 16 '05 #6
> Thx. for help. I think that there is similar problem when thread ends: it
sets the flag that is not busy (last statement in thread), but thread will
be actualy terminated few milliseconds after.
I don't see a problem there. The thread will end some time after, but since
it wont do any work you don't have to worry. Anyways next time you'll create
a new one
achieve same functionality like in example and to get complete
synchronization?


I presonally don't see anything wrong with that one. You shouldn't go too
complex for such simple sync scenario

--

Stoitcho Goutsev (100) [C# MVP]

Nov 16 '05 #7
Thx. your comments are very helpful.

Best regards
Ivan
"Stoitcho Goutsev (100) [C# MVP]" <10*@100.com> wrote in message
news:eD**************@TK2MSFTNGP10.phx.gbl...
Thx. for help. I think that there is similar problem when thread ends: it sets the flag that is not busy (last statement in thread), but thread will be actualy terminated few milliseconds after.
I don't see a problem there. The thread will end some time after, but

since it wont do any work you don't have to worry. Anyways next time you'll create a new one
achieve same functionality like in example and to get complete
synchronization?


I presonally don't see anything wrong with that one. You shouldn't go too
complex for such simple sync scenario

--

Stoitcho Goutsev (100) [C# MVP]

Nov 16 '05 #8

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

Similar topics

0
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can...
4
by: scott | last post by:
hi all, Thx to any one that can offer me help, it will be much appreciated. iv got a multithreaded program and need to use thread synchronization. The synchronization does not have to...
20
by: Bob Day | last post by:
Using VS 2003, VB, MSDE... There are two threads, A & B, that continously run and are started by Sub Main. They instantiationsl of identical code. Thread A handles call activity on telephone...
6
by: Robert Speck | last post by:
Hi there, Can anyone shed anymore light on why "Thread.Suspend()" has been deprecated by MSFT beyond what MSDN says about it. I'm not sure if I quite appreciate the various pitfalls they discuss...
4
by: fniles | last post by:
I create a thread where I pass thru a message. When I click very fast many times (like 50 times) to create 50 threads, the message did not get pass thru ProcessMessage. For example: strBuffer =...
13
by: arun.darra | last post by:
Are the following thread safe: 1. Assuming Object is any simple object Object* fn() { Object *p = new Object(); return p; } 2. is return by value thread safe?
0
by: sundman.anders | last post by:
Hi all! I have a question about thread synchronization and c++ streams (iostreams, stringstreams, etc). When optimizing a program for a multicore processor I found that stringstream was causing...
19
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
8
by: Markus | last post by:
Hello everyone. Recently I stumbled upon an interesting problem related to thread-parallel programming in C (and similarily C++). As an example assume a simple "buffer" array of size 8, e.g....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
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,...
0
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...
0
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...

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.