473,545 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

N threads synchronization - contrived example

Hi

Say you had N threads doing some jobs (not from a shared queue or
anything like that, they each know how to do their own set of jobs in a
self-contained way). How can you coordinate them so that they all wait
until they've all done one job before starting off on each of their
next jobs.

I have been thinking about this for a day and can't seem to find a
solution.

Emma

Oct 13 '06 #1
12 1994
You could wait on an autoreset event that gets set after last job finished
or use Thread.Join to wait on N threads to finish job 1 and exit, then start
more threads for job 2, etc.

--
William Stacey [C# MVP]

<em************ **@fastmail.fmw rote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
| Hi
|
| Say you had N threads doing some jobs (not from a shared queue or
| anything like that, they each know how to do their own set of jobs in a
| self-contained way). How can you coordinate them so that they all wait
| until they've all done one job before starting off on each of their
| next jobs.
|
| I have been thinking about this for a day and can't seem to find a
| solution.
|
| Emma
|
Oct 13 '06 #2
William Stacey [C# MVP] wrote:
You could wait on an autoreset event that gets set after last job finished
or use Thread.Join to wait on N threads to finish job 1 and exit, then start
more threads for job 2, etc
That's given me some good ideas! I was thinking that the threads
shouldn't know about each other directly, and also my abstract problem
includes that there is nothing as such that is coordinating them. In
order to coordinate themselves, the AutoResetEvent idea is what I tried
initially but couldn't get it to work. Do you think a Semaphore is what
I should use? I'm finding it a bit hard to get it working though!

Emma.

Oct 13 '06 #3
em************* *@fastmail.fm wrote:
William Stacey [C# MVP] wrote:
You could wait on an autoreset event that gets set after last job finished
or use Thread.Join to wait on N threads to finish job 1 and exit, then start
more threads for job 2, etc

That's given me some good ideas! I was thinking that the threads
shouldn't know about each other directly, and also my abstract problem
includes that there is nothing as such that is coordinating them. In
order to coordinate themselves, the AutoResetEvent idea is what I tried
initially but couldn't get it to work. Do you think a Semaphore is what
I should use? I'm finding it a bit hard to get it working though!
Hi

So, I got a quick moment to knock up something that works ...

It uses N AutoResetEvents and each thread waits on its own event, then
signals the next one when finished, in circular fashion.

Is this the best I can do (i.e. I must use N synchronization objects)?
Can someone confirm that, if I want the threads to process jobs in this
particular order and one at a time, there is no better way?

Here's a related question: if I just want threads to all complete one
job before any other thread can go on to the next one (i.e. dump out
the next int!) but it doesn't have to be in any particular thread
order, can I use just 1 synchronization object? I'm trying to get the
Semaphore to work in this situation because it seems exactly what's
required!

If anyone is interested, fancies adapting and improving, I've enclosed
below a working program just in case:

static void Main()
{
int threadCount;

while (true)
{
Console.Write(" Enter number of threads: ");
string input = Console.ReadLin e();

if (int.TryParse(i nput, out threadCount) && threadCount
0)
{
break;
}

Console.WriteLi ne("Enter a positive integer.");
}

AutoResetEvent[] events = new AutoResetEvent[threadCount];
ThreadConsole[] threads = new ThreadConsole[threadCount];

for (int i = 0; i < threadCount; i++)
{
events[i] = new AutoResetEvent( false);
}

for (int i = 0; i < threadCount; i++)
{
threads[i] = new ThreadConsole(" Thread " +
i.ToString(), events[i], events[i + 1 == threadCount ? 0 : i + 1]);
threads[i].Start();
}

events[0].Set();

Console.ReadLin e();
}
}

class ThreadConsole
{
Thread thread;
string name;
AutoResetEvent canStart;
AutoResetEvent nextCanStart;

public ThreadConsole(s tring name, AutoResetEvent canStart,
AutoResetEvent nextcanStart)
{
thread = new Thread(ThreadPr oc);
this.name = name;
this.canStart = canStart;
this.nextCanSta rt = nextcanStart;
}

public void Start()
{
thread.Start();
}

void ThreadProc()
{
for (int i = 0; i < 100; i++)
{
canStart.WaitOn e();
Console.WriteLi ne(name + ": " + i.ToString());
nextCanStart.Se t();
}
}
}
Cheers,

Emma.

Oct 15 '06 #4
Is this the best I can do (i.e. I must use N synchronization objects)?
Can someone confirm that, if I want the threads to process jobs in this
particular order and one at a time, there is no better way?
You don't state what you mean by "better way". In terms of number of
synchronization objects needed, the minimal number of synchronization
objects needed to serialize N jobs is log2 N, but in terms of
understandabili ty, using the logN solution would not be the "better way".
Oct 15 '06 #5

Lebesgue wrote:
Is this the best I can do (i.e. I must use N synchronization objects)?
Can someone confirm that, if I want the threads to process jobs in this
particular order and one at a time, there is no better way?

You don't state what you mean by "better way". In terms of number of
synchronization objects needed, the minimal number of synchronization
objects needed to serialize N jobs is log2 N, but in terms of
understandabili ty, using the logN solution would not be the "better way".
Yes, in terms of the number of synchronization objects.

What I suppose I'm asking is what is the standard way to do what I'm
trying to do? By standard, I mean common/well-known/popular (and so
that might imply most readable as well). I have a feeling in the back
of my mind that there must be something more elegant, but maybe not.

For instance, it really feels as if the problem can be solved with one
synchronization object, if we relax the constraint that the threads
must do one job at at time and in order i.e. if they just have to do
one job at a time and in any thread order. I keep on looking at
semaphores but they don't 'enforce thread identity' as the help puts
it! I'll keep on thinking about this until someone tells me it can't be
done (which would be helpful so I can move on!).

Finally, I presume logN solution is using the synchronization objects
as binary digits and operating on them like that - e.g. thread 6
carries on when event 0, 2 are signalled and 1 is not! Yes, I agree
that it would certainly be a little more fiddly to read, nice idea
though.

Thanks very much,

Emma.

Oct 15 '06 #6
Please provide a senerio using a description of tasks. That would help I
think.

--
William Stacey [C# MVP]

<em************ **@fastmail.fmw rote in message
news:11******** **************@ f16g2000cwb.goo glegroups.com.. .
|
| Lebesgue wrote:
| Is this the best I can do (i.e. I must use N synchronization objects)?
| Can someone confirm that, if I want the threads to process jobs in
this
| particular order and one at a time, there is no better way?
|
| >
| You don't state what you mean by "better way". In terms of number of
| synchronization objects needed, the minimal number of synchronization
| objects needed to serialize N jobs is log2 N, but in terms of
| understandabili ty, using the logN solution would not be the "better
way".
|
| Yes, in terms of the number of synchronization objects.
|
| What I suppose I'm asking is what is the standard way to do what I'm
| trying to do? By standard, I mean common/well-known/popular (and so
| that might imply most readable as well). I have a feeling in the back
| of my mind that there must be something more elegant, but maybe not.
|
| For instance, it really feels as if the problem can be solved with one
| synchronization object, if we relax the constraint that the threads
| must do one job at at time and in order i.e. if they just have to do
| one job at a time and in any thread order. I keep on looking at
| semaphores but they don't 'enforce thread identity' as the help puts
| it! I'll keep on thinking about this until someone tells me it can't be
| done (which would be helpful so I can move on!).
|
| Finally, I presume logN solution is using the synchronization objects
| as binary digits and operating on them like that - e.g. thread 6
| carries on when event 0, 2 are signalled and 1 is not! Yes, I agree
| that it would certainly be a little more fiddly to read, nice idea
| though.
|
| Thanks very much,
|
| Emma.
|
Oct 15 '06 #7
William Stacey [C# MVP] wrote:
Please provide a senerio using a description of tasks. That would help I
think.
Hi

The solution I posted works for the case where there are N threads and
the threads have to be scheduled in order - it follows your AutoReset
idea - or at least your suggestion gave me the idea for that
implementation - is that what you had in mind by the way? The point of
the iteration and the output is to simulate an arbitrary task so we
have as much information as we're going to get! I admit that this could
be seen as a relatively stupid question because there are N threads
effectively being serialized despite the fact that they're working on
separate data ...

Anyway, I'm now just thinking whether or not I can achieve similar with
less than N synch objects, in particular when the order of the threads
processing jobs doesn't matter but they all have to process one job
before any thread can process another job.

There's a post above that says it can be done with log N but, although
I thought I could see how, I can't any more. Not, in the sense of e.g.
an Event in the Win32 sense because you can't block on a non-signalled
event!

So, I've now got three questions! How to get the log N version to work?
Is there any difference between the number of synchronization objects
in the case I've already posted code for, and the case where the order
of threads doesn't matter, as outlined above. And finally, what other
ways are there and can Semaphores help?

Cheers.

Emma.

Oct 15 '06 #8
Lebesgue wrote:
Is this the best I can do (i.e. I must use N synchronization objects)?
Can someone confirm that, if I want the threads to process jobs in this
particular order and one at a time, there is no better way?

You don't state what you mean by "better way". In terms of number of
synchronization objects needed, the minimal number of synchronization
objects needed to serialize N jobs is log2 N, but in terms of
understandabili ty, using the logN solution would not be the "better way".
Hi

As I said in a previous post, I thought I understood the way to do the
logN synch objects but now I'm not so sure. I can't even think how to
achieve what my posted code does but with only 2 threads and 1 synch
object i.e. the simplest case!

Would you be able to outline?

Thanks!

Emma.

Oct 15 '06 #9
As you have correctly stated in your previous post, the magic is in encoding
the order of the threads in binary.

Let's assume you have threads T0 T1 T2 T3 you want to serialize in such a
way that T1 starts after T0 has completed its job and so on.

Then we encode the order as shown in this table:

T0 T1 T2 T3
S1 0 0 1 1
S2 0 1 0 1

Each thread has unique combination of binary semaphores to wait for (1 means
to wait for the particular semaphore) and the previous thread ensures to
configure the semaphores to be in required combination.
When there are more threads in order to wait for the same semaphore (T2 and
T3 both wait for S1), the event needs to be signalled twice (as many times
as the number of threads to wait for the same object in a row).

In terms of implementation, I have implemented and tested this using binary
semaphores. I believe it could be implemented using eventwaithandle s, but
have not tried so far - if there is an abvious reason it could not be
implemented using waithandles, I don't see it now, since it's midnight.

I just found out there is a solution with (constant) 3 semaphores, which is
the optimal solution in terms of number of synchronization objects needed,
but if logN solution makes it less readable, const3 solution would make it
unreadable.

Hope this helps.

<em************ **@fastmail.fmw rote in message
news:11******** **************@ m7g2000cwm.goog legroups.com...
Lebesgue wrote:
Is this the best I can do (i.e. I must use N synchronization objects)?
Can someone confirm that, if I want the threads to process jobs in this
particular order and one at a time, there is no better way?

You don't state what you mean by "better way". In terms of number of
synchronizatio n objects needed, the minimal number of synchronization
objects needed to serialize N jobs is log2 N, but in terms of
understandabil ity, using the logN solution would not be the "better way".

Hi

As I said in a previous post, I thought I understood the way to do the
logN synch objects but now I'm not so sure. I can't even think how to
achieve what my posted code does but with only 2 threads and 1 synch
object i.e. the simplest case!

Would you be able to outline?

Thanks!

Emma.

Oct 15 '06 #10

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

Similar topics

28
1852
by: Dennis Owens | last post by:
I am trying to run a thread off of a form, and every once in a while the thread will raise an event for the form to read. When the form gets the event, the form will place the event into a dataset and display it on a datagrid that is on the form. The problem is that the thread will slowly take over all of the processor time. After about 8 events,...
6
2389
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...
22
4031
by: Jeff Louie | last post by:
Well I wonder if my old brain can handle threading. Dose this code look reasonable. Regards, Jeff using System; using System.Diagnostics; using System.IO; using System.Threading;
10
1661
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,
4
1625
by: sir_alex | last post by:
Hello everybody! I have a couple of questions about threads: the first is, is there the possibility to cancel a thread while it is executing (like the C function thread_cancel), for implementing something like an "abort" button? And the second is, i have a GUI in which there's a button that launches a thread implemented using the threading...
9
1706
by: bonk | last post by:
Does anyone have a simple example on how to prohibit that any thread other than the current thread modifies a certain object (a collection) while we are in a certain section of the code? In other words: while we are inside this codeblock whoever might think of modified that particular collection has to wait until we have left that codeblock....
18
2242
by: Jon Slaughter | last post by:
"Instead of just waiting for its time slice to expire, a thread can block each time it initiates a time-consuming activity in another thread until the activity finishes. This is better than spinning in a polling loop waiting for completion because it allows other threads to run sooner than they would if the system had to rely solely on...
167
8168
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++...
23
4250
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...
0
7467
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...
0
7401
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...
1
7419
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...
0
5971
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...
1
5326
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...
0
4944
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...
0
3450
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...
0
3442
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1879
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

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.