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

limiting simultaniously executing threads

Hi All,
I have a block of code. I don't want more than five threads to enter
this block simultaneously...

Some thing like this

lock(MyObject)
{
....do work here.
}

so this will allow only one thread to enter at once .

what i want is a effect like

lock(MyObject1) || lock(MyObject2) || lock(MyObject3) ||
lock(MyObject4) || lock(MyObject5)
{
....do work here.
}

This obviously does not compile.
so how can i do this .
1)Do i have to write my own thread pool and limit the number of threads
to 5?
2)Can i do it using using the thread pool class provided in .net ?
3)Can i do it with without using any of the thread Pool class (.net
threadPool or custom thread pool class ) instead use some specific type
of lock to achieve this.

...may be i can maintain some counter and make thread sleep for some
time ..but...I am thinking there might be a better and more clean
solution than this one...

Appreciate any ideas...

Thanks
Sidd

Aug 16 '05 #1
3 1463
What you need to use is Semaphore, which would be the most elegant solution.
Semaphores are not implemented in .NET (I hope someone here will explain
why).
But .NET provides us with WaitHandles - AutoResetEvents and
ManualResetEvents and WaitHandle.WaitAll/Any methods which can help you with
solving this issue.

Definition of semaphore
http://en.wikipedia.org/wiki/Semapho...programming%29

<si************@hotmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Hi All,
I have a block of code. I don't want more than five threads to enter
this block simultaneously...

Some thing like this

lock(MyObject)
{
....do work here.
}

so this will allow only one thread to enter at once .

what i want is a effect like

lock(MyObject1) || lock(MyObject2) || lock(MyObject3) ||
lock(MyObject4) || lock(MyObject5)
{
....do work here.
}

This obviously does not compile.
so how can i do this .
1)Do i have to write my own thread pool and limit the number of threads
to 5?
2)Can i do it using using the thread pool class provided in .net ?
3)Can i do it with without using any of the thread Pool class (.net
threadPool or custom thread pool class ) instead use some specific type
of lock to achieve this.

..may be i can maintain some counter and make thread sleep for some
time ..but...I am thinking there might be a better and more clean
solution than this one...

Appreciate any ideas...

Thanks
Sidd

Aug 16 '05 #2
Lebesgue <no****@spam.jp> wrote:
What you need to use is Semaphore, which would be the most elegant solution.
Agreed.
Semaphores are not implemented in .NET (I hope someone here will explain
why).
I think it was just an oversight, really.
But .NET provides us with WaitHandles - AutoResetEvents and
ManualResetEvents and WaitHandle.WaitAll/Any methods which can help you with
solving this issue.


Alternatively, it's pretty easy to write a semaphore using
Monitor.Wait/Pulse, which is a more "natively .NET" way of doing
things.

I'm sure there are plenty of semaphore implementations available on the
net - I must include one in MiscUtil some time...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Aug 17 '05 #3
Hi Sidd,
Here I provide a sample Semaphore implementation using Win32 API. I hope it
will be helpful to you.
usage:

Semaphore s = new Semaphore(5, true);

s.Wait();
//a maximum of 5 threads will be allowed in this section
s.Signal();

//<code>
using System.Runtime.InteropServices;

namespace System
{
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}

internal enum WaitResult
{
WAIT_ABANDONED = 0x00000080,
WAIT_IO_COMPLETION = 0x000000C0,
WAIT_OBJECT_0 = 0x00000000,
WAIT_TIMEOUT = 0x00000102
}

/// <summary>
/// Summary description for Semaphore.
/// </summary>
public class Semaphore : IDisposable
{
private IntPtr hSemaphore;

[DllImport("kernel32.dll", SetLastError=true)]
private static extern IntPtr CreateSemaphore(ref SECURITY_ATTRIBUTES
securityAttributes, int initialCount, int maximumCount, string name);
[DllImport("kernel32.dll")]
private static extern bool ReleaseSemaphore(IntPtr hSemaphore, int
lReleaseCount, IntPtr lpPreviousCount);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32", SetLastError=true, ExactSpelling=true)]
private static extern Int32 WaitForSingleObject(IntPtr handle, Int32
milliseconds);

private static uint INFINITE = 0xFFFFFFFF;

/// <summary>
/// Creates a semaphore initialized in it's nonsignalled state
/// </summary>
/// <param name="maxCount">maximum number of threads</param>
public Semaphore(int maxCount) : this(maxCount, false)
{
}

public Semaphore(int maxCount, bool initiallySignalled) :
this(initiallySignalled ? maxCount : 0, maxCount)
{

}

public Semaphore(int initialCount, int maxCount) : this(initialCount,
maxCount, null)
{

}

protected Semaphore(int initialCount, int maxCount, string name)
{
if (maxCount < 0 || initialCount < 0)
{
throw new ArgumentException("initialCount and maximumCount must not be
negative");
}

if (initialCount > maxCount)
{
throw new ArgumentException("initialCount must not be more than
maximumCount", "initialCount");
}

SECURITY_ATTRIBUTES attr = new SECURITY_ATTRIBUTES();

hSemaphore = CreateSemaphore(ref attr, initialCount, maxCount, name);
if (hSemaphore == IntPtr.Zero)
{
int error = System.Runtime.InteropServices.Marshal.GetLastWin3 2Error();
throw new ApplicationException("Semaphore could not be created, error
code: " + error);
}
}

public void Dispose()
{
try
{
CloseHandle(hSemaphore);
}
finally
{
hSemaphore = IntPtr.Zero;
}
}

public void Wait()
{
int o = WaitForSingleObject(hSemaphore, (int)INFINITE);
WaitResult r = (WaitResult)o;
}

public void Signal()
{
if (!ReleaseSemaphore(hSemaphore, 1, IntPtr.Zero))
{
int error = System.Runtime.InteropServices.Marshal.GetLastWin3 2Error();
if (error == 0)
{
throw new ApplicationException("Semaphore was already in it's signalled
state");
}
else
{
throw new ApplicationException("Semaphore could not be released, error
code: " + error);
}
}
}
}
}
//</code>
Aug 17 '05 #4

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

Similar topics

2
by: TheDustbustr | last post by:
I'm writing a game in C++ that calls out to Python for scripting. The C++ kernel holds an instance of ScriptCtl and calls the load(filename) method to load a script, then run() to run all loaded...
2
by: murray_shane56 | last post by:
We currently have a routine that "forks" out (to use the unix term)TSQL commands to run asynchronously via SQL Agent jobs. Each TSQL command gets its own Job, and the job starts immediately after...
5
by: randyelliott | last post by:
Good Day, I have a MS Access (Access 2000 now upgraded to 2003) database that tracks customer information. One function of this database is to create an encrypted license file for our software,...
2
by: Tony Liu | last post by:
Hi, I want to get the name of the calling function of an executing function, I use the StackTrace class to do this and it seems working. However, does anyone think that there any side effect...
10
by: Mike | last post by:
I know this sounds strange but I am at a loss. I am calling a simple funtion that opens a connection to a SQL Server 2000 database and executes an Insert Statement. private void...
3
by: siddharthkhare | last post by:
Hi All, I have a block of code. I don't want more than five threads to enter this block simultaneously... Some thing like this lock(MyObject) { ....do work here. }
0
by: BasicQ | last post by:
I am running an executable from my aspx page with the click of a button. A date is passed as an argument. I am able to get the standardoutput from the Process(Exe) into the label of my page after...
1
by: Jon | last post by:
My question is: Can the Garbage Collector (GC) suspended a managed thread while it is executing native code. The reason I am interested in this is that I have: 1) a native thread (N) that only...
0
Jacotheron
by: Jacotheron | last post by:
Hi I have a database which should return data of the threads. The idea is to create a small community (only selected users may participate) where they can post their statements etc for others to see...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.