473,739 Members | 7,912 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.EventArg s 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.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " started");
Thread.Sleep (5000);
Debug.WriteLine ("Thread num. " + Convert.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " finished");
IsRunning = false;
}

public bool IsRunning
{
get
{
lock (status)
{
return status.isRunnin g;
}
}
set
{
lock (status)
{
status.isRunnin g = 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 2703
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.co m>
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.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
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.co m>
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.co m>
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.WriteLi ne ("Thread num. " + Convert.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " started");
Thread.Sleep (5000);
Console.WriteLi ne ("Thread num. " + Convert.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " 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.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
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.co m>
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******** ******@TK2MSFTN GP10.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.WriteLi ne ("Thread num. " + Convert.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " started");
Thread.Sleep (5000);
Console.WriteLi ne ("Thread num. " + Convert.ToStrin g
(Thread.Current Thread.GetHashC ode ()) + " 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.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
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.co m>
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******** ******@TK2MSFTN GP10.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
375
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 fail if the event is emptied of all methods between the two statements, implying that some sort of synchronization between this and removals from EventName is needed. The other problem is that if an event with a set of delegates is in the process...
4
3201
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 work across multiple processes just the one. I was wondering if any one new which one used the least overhead. Im at current using mutexes but was wondering if there was something a bit
20
2414
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 line 1 and Thread B handles call activity on telephone line 2. They use a common SQL datasource, but all DataSets are unique to each thread. Is there a way for thread A to occasionally communication to thread B that something has happened? ...
6
1418
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 but using it under certain circumstances still seems reasonable. For instance, I want to display a small modal dialog with a "Cancel" button which allows the user to abort a background thread. If the user clicks this button, I then want to prompt...
4
1419
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 = "#TRADE, D1410-123456, BUY, 1, ESM7, DAY, LIMIT, 1490.00, , , 0, 0, 0, 0, 0, links |52994/25/2007 10:47:17 AM !A", when I trigger to create many threads (like 50), this message did not get to sub ProcessMessage in clsEachMessage. I have added...
13
3601
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
1978
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 a LOT of synchronization overhead. After a bit of digging I concluded that this synchronization has to do with the access to a global locale inside the stream. The problem can be seen by running the small distilled benchmark code
19
2310
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
1425
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. with static lifetime and exteral linkage. One thread fills the buffer structure, and the other in some way evaluates its contents, e.g. do { synchronize_with_other_thread(); for (int i=0;i<8;++i) {
0
8969
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
9337
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
9266
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
8215
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
6754
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
4826
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3280
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
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.