473,406 Members | 2,439 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,406 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

Nov 17 '05 #1
3 1409
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

Nov 17 '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
Nov 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>
Nov 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...
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. }
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...
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...
2
by: acw | last post by:
On a SQL Server 2000 db I would like to setup a stored procedure that accesses couple tables and runs the extended stored procedure xp..cmdshell. The goal is to grant users with limited privileges...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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:
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
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,...
0
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...

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.