threadpool: how can I make sure just an X amount of threads (CPU's) are used?

Hi,

I've made a test project to see how the CPU usage will react based on
the example given on: http://msdn.microsoft.com/en-us/library/system.thread=
ing.threadpool.queueuserworkitem(VS.71).aspx
The code is below.

What I want to achieve is to be able to make sure that for a number of
task send to the threadpool (or any other solution), I will only use x
number of CPU=92s. With the code below, it doesn=92t matter how I set
ThreadPool.SetMaxThreads and ThreadPool.SetMinThreads, when I run the
program, all my CPU=92s are consumed. I=92ve tested this on a computer
with 2 and with 8 cores. Also the 8 core computer use all cores.

What do I need to do to get it working properly?
Kind regards,

Matthijs


// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
using System;
using System.Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo
{
    // State information for the task.  These members
    // can be implemented as read-only properties, read/write
    // properties with validation, and so on, as required.
    public string Boilerplate;
    public int Value;
    public int CurrentACtiveThreads;

    // Public constructor provides an easy way to supply all
    // the information needed for the task.
    public TaskInfo(string text, int number, int activeThreads)
    {
        Boilerplate =3D text;
        Value =3D number;
        CurrentACtiveThreads =3D activeThreads;
    }
}

public class Example
{
    public static void Main()
    {
        // Create an object containing the information needed
        // for the task.

        // Queue the task and data.
        ThreadPool.SetMaxThreads(2, 1);
        ThreadPool.SetMinThreads(1, 1);

        int availableThread,completionPortThreads;

        for (int i =3D 0; i < 100; i++)
        {
            ThreadPool.GetAvailableThreads(out availableThread, out
completionPortThreads);
            TaskInfo ti =3D new TaskInfo("This report displays the
number",i,availableThread);
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc),
ti);
            Thread.Sleep(50);
        }
        Console.WriteLine("Main thread does some work, then sleeps.");

        // If you comment out the Sleep, the main thread exits before
        // the ThreadPool task has a chance to run.  ThreadPool uses
        // background threads, which do not keep the application
        // running.  (This is a simple example of a race condition.)

        Thread.Sleep(100000);

        Console.WriteLine("Main thread exits.");
    }

    // The thread procedure performs the independent task, in this
case
    // formatting and printing a very simple report.
    //
    static void ThreadProc(Object stateInfo)
    {
        TaskInfo ti =3D (TaskInfo)stateInfo;
        Console.WriteLine(ti.Boilerplate + " " + ti.Value +" " +
ti.CurrentACtiveThreads);
        for (int i =3D 0; i < 10000000; i++)
        {
            Math.Sqrt(Math.Sin(i));
            Math.Tan(Math.Sqrt(Math.Sin(i)));
        }
    }
}

0
Matthijs
4/15/2010 2:36:37 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

6 Replies
1279 Views

Similar Articles

[PageSpeed] 51

Matthijs de Z wrote:
> Hi,
> 
> I've made a test project to see how the CPU usage will react based on
> the example given on: http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem(VS.71).aspx
> The code is below.
> 
> What I want to achieve is to be able to make sure that for a number of
> task send to the threadpool (or any other solution), I will only use x
> number of CPU�s. With the code below, it doesn�t matter how I set
> ThreadPool.SetMaxThreads and ThreadPool.SetMinThreads, when I run the
> program, all my CPU�s are consumed. I�ve tested this on a computer
> with 2 and with 8 cores. Also the 8 core computer use all cores.
> 
> What do I need to do to get it working properly?

Either don't use ThreadPool (which will always try to run all of the 
work items that have been queued), or don't queue more work items than 
you want running at once.

You definitely do not want to mess around with SetMaxThreads().  The 
ThreadPool is used not just by your own code, but by a variety of other 
..NET components.

It won't have the effect you want anyway � as the documentation clearly 
states, "You cannot set the number of worker threads or the number of 
I/O completion threads to a number smaller than the number of processors 
in the computer", so it's not a useful way to restrict how many CPU 
cores are used at once � and it can have a serious negative effect on 
the efficiency of the other components that use the ThreadPool class.

It is not very hard to set up your own queue to use as a sort of 
"gatekeeper" to restrict how many work items you've actually queued at 
once.  In fact, I'm pretty sure I posted an example of doing that in 
this newsgroup some time ago; Google Groups search can probably find the 
code for you.  Alternatively, I don't recall for sure, but I think maybe 
Jon Skeet's "MiscUtil" library's custom thread pool implementation might 
support what you want to do.  You can find that library here:
http://www.yoda.arachsys.com/csharp/miscutil/

Pete
0
Peter
4/15/2010 3:34:59 PM
> It is not very hard to set up your own queue to use as a sort of
> "gatekeeper" to restrict how many work items you've actually queued at
> once. =A0In fact, I'm pretty sure I posted an example of doing that in
> this newsgroup some time ago; Google Groups search can probably find the
> code for you. =A0Alternatively, I don't recall for sure, but I think mayb=
e
> Jon Skeet's "MiscUtil" library's custom thread pool implementation might
> support what you want to do. =A0You can find that library here:http://www=
..yoda.arachsys.com/csharp/miscutil/

> Pete

Hi Peter,

thanks for your responds.
I've been googling around using
group:microsoft.public.dotnet.languages.csharp author:"peter duniho"
and some keywords, but it seems you're a very active newsgroup writer
(helping out people). I was not able to find the article you refer to.
Do you recall a subject for that, to narrow down my search?
Kind regards,

Matthijs

0
Matthijs
4/16/2010 7:41:48 AM
Matthijs de Z wrote:
> thanks for your responds.
> I've been googling around using
> group:microsoft.public.dotnet.languages.csharp author:"peter duniho"
> and some keywords, but it seems you're a very active newsgroup writer
> (helping out people). I was not able to find the article you refer to.
> Do you recall a subject for that, to narrow down my search?
> Kind regards,

I looked around, and found a couple of posts that might be helpful:
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/2064ea48b0a9a1a4
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/0d3b7aee7712b07e

The second example is much more complicated, but the portion of it that 
deals with limiting concurrent tasks is probably more directly relevant 
to your question, and isn't itself all that complicated.  See the 
"DownloadManager" class.

The first example actually accomplishes a very similar outcome, and by 
virtue of using the BackgroundWorker winds up using the ThreadPool. 
Note, however, that the particular code I posted is specifically 
dependent on the BackgroundWorker being used in a context where there's 
a SynchronizationContext to handle cross-thread invocations (e.g. a 
Forms GUI thread, where Application.Run() has been called).  Without 
that, the code I posted before would need additional synchronization 
dealing with the queue of tasks.

If you have questions about either of those, please feel free to ask. 
In general, the basic idea is: keep a counter of how many concurrent 
tasks you've already sent off for processing (by whatever means), 
queuing any tasks added when the counter is already at the maximum, and 
dequeuing a new task to process when a running task is completed.

There are lots of ways to accomplish that, but they all share that same 
basic strategy.

Pete
0
Peter
4/16/2010 9:20:00 AM
I looked around, and found a couple of posts that might be helpful:
http://groups.google.com/group/microsoft.public.dotnet.languages.csha...
http://groups.google.com/group/microsoft.public.dotnet.languages.csha...

Thanks Pete!

> There are lots of ways to accomplish that, but they all share that same
> basic strategy.
>
> Pete

0
Matthijs
4/16/2010 11:55:07 AM
> Peter Duniho wrote:
> I looked around, and found a couple of posts that might be helpful:

http://www.google.com/url?sa=D&q=http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/2064ea48b0a9a1a4&usg=AFQjCNEMBLUXsXGAHbO4OTmUZVdBzSuJ-A

This (above) was exactly what I needed for now.

http://www.google.com/url?sa=D&q=http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/0d3b7aee7712b07e&usg=AFQjCNEm7wSKk2CpDbg6kjGfrhL3ydsTfw

And this, I can probably use for something else.
Thanks a lot.
regards,

Matthijs
0
Matthijs
4/16/2010 12:25:59 PM
On 16 apr, 13:55, Matthijs de Z <matthijsdezw...@gmail.com> wrote:
> I looked around, and found a couple of posts that might be helpful:http://groups.google.com/group/microsoft.public.dotnet.languages.csha...http://groups.google.com/group/microsoft.public.dotnet.languages.csha...
>
> Thanks Pete!
>
>
>
> > There are lots of ways to accomplish that, but they all share that same
> > basic strategy.
>
> > Pete- Tekst uit oorspronkelijk bericht niet weergeven -
>
> - Tekst uit oorspronkelijk bericht weergeven -

0
Matthijs
4/16/2010 12:26:14 PM
Reply:

Similar Artilces:

Can I create a thread safe Winform User Control
Hi, I know that if I want to update a Windows Form Control from a worker thread I need to check InvokeRequired on the control and jump through some hoops. I can get that all to work. But, I wonder if I can make a User Control which inherits from for example, System.Windows.Forms.Label, and has the correct thread safe set method built in? In fact, why are Windows Forms controls not thread safe? It seems like it would have been pretty easy to build in, at least for the their simple properties, and would save a fair amount of fiddly work on the developer's part. Thanks, ...

can't move email twice; can't see text in mail moved to directory
i can drag and drop an email from the inbox to another folder (lets say A) in outlook. but if i try to drag if from that folder (A) to another folder (B), i get an error message saying the email can not be moved ??? why can't i move the email a second time? *** if i drag the email to a directory on my hard drive, i can see the email with explorer, and it has a file size, but when i click on it i only get a blank email screen in outlook ??? why can't i see the email text when the file is on the hard drive? ...

Error message when using outlook connector for Lotus
I keep getting an error message, "Notes Termination skipped because a thread has not terminated. Please reboot" when Outlook is started. I am using Outlook Connector for Lotus. The error goes away on clicking 'OK', but keeps recurring time and again. Nothing seems to get rid of this annoying message. Tried to uninstall the Outlook conenctor and install the new version of Outlook connector, but of no avail. Can anybody tell me the way to get rid of this problem? Thanks, VS hi i've the same problem Do you have any solutions thank Marve -- Marve -----------------------...

Can you make a scatter graft
I am wanting to make a scatter graft or dot graft but do not know how Put your X values into one column, and your Y values into the next column, and if you want to name the series of points, put the label into the cell just above the first Y value. Select the data, and run the chart wizard (the little chart icon on the standard toolbar, or go to Insert menu > Chart). In step one, choose an XY Scatter type, then continue through the wizard. - Jon ------- Jon Peltier, Microsoft Excel MVP Peltier Technical Services Tutorials and Custom Solutions http://PeltierTech.com/ _______ Leanne ...

Have excel queries use current directory
I have a workbook with 6 excel saved queries and pivot tables based on an Access Database. Each month I copy the entire contents of the folder to a new folder (example DbPop200404Apr gets copied to DBPop200405May). The access database gets updated and I want the excel pivot tables and charts to reflect this data. The queries on each worksheet still relate back to the original, even though I edit each DQY to reflect the new directory. I have to go each worksheet and reconstruct the query. How do you make excel automatically use the DQYs in the CURRENT directory where the workbook res...

RecieveGif can only save as bmp
I had the same problem with IE, I looked the problem up and fixed it. But I can find no fix for outlook e-mail msgs I get a gif file and will only save as BMP. i f I add another extension to it like Gif for an animated gif it will not be an animated gif. You can use this code to create a macro that will do it for you. Funny that you mention it as I'm going to issue a newsletter about this tomorrow with step by step details. Sub SaveAttachment() Dim objCurrentItem As Outlook.MailItem Dim colAttachments As Outlook.Attachments Dim objAttachment As Outlook.Attachment Set objCurren...

When to use ThreadPool
Hi! Here is some text from e-learning. What does it mean when the text says "don't require scheduling of your thread's execution" ? *ThreadPool class is best suited for use when your threads are performing short tasks or when you don't require scheduling of your thread's execution.* //Tony Forget this question //Tony "Tony Johansson" <johansson.andersson@telia.com> skrev i meddelandet news:%23z5nXh58KHA.3276@TK2MSFTNGP02.phx.gbl... > Hi! > > Here is some text from e-learning. What does it mean when the text says...

Setting folder for offline use
In Microsoft Outlook 2002, I creating a new profile using a certain %username%. How do I set the folder for offline use? Some background info...I am also going to configure this for the exchange server. Ryan <rw_gilbert@hotmail.com> wrote: > In Microsoft Outlook 2002, I creating a new profile using > a certain %username%. How do I set the folder for offline > use? > > Some background info...I am also going to configure this > for the exchange server. It's on the Properties page for the Email account. -- Brian Tillman Smiths Aerospace 3290 Patte...

how to write an amount in words through formula
please tell me how i can write a figure in the form of text i.e Amount in Words, please send the code to me in my hotmail inbox my email is abbas_niazi@hotmail.com --- Message posted from http://www.ExcelForum.com/ This file might be a help: http://www.bygsoftware.com/examples/zipfiles/num2wrds.zip It's in the "Accountants" section on page: http://www.bygsoftware.com/examples/examples.htm It contains two methods to convert numbers to words and two cheque writing routines. The code is open and commented. As a general rule all replies should be to the newsgroup (in this inst...

How Can I This Function Please
Hi, I found this article about validating Postcodes and would really like to use it. http://www.mvps.org/access/modules/mdl0063.htm I have copied the code to a new module and on my Data Input Form and have used this code for the field Postcode; Private Sub Postcode_BeforeUpdate(Cancel As Integer) If Not rgxValidate([Postcode], rgxZIP_UK) Then MsgBox "I don't like " & Me.Postcode Cancel = True End If End Sub However when I compile, it tells me that rgxvalidate is a ambiguous name even though, I have only copied it once. Am I not calling the function prope...

Can not receive emals in Outlook 2003
Very frustrated here. Can not figure this one out. have a laptop that cratered one me.. Windows XP.....I had to do a system restore from the beginning. Lost a lot but no biggie. Had Office 97 full version on it and then had the 2003 Office Upgrade. Had no problems before it crashed. Got everything fixed on the laptop. Got all the windows updated and went to upload the Office again and had problems right off the bat with 97. Couldnt find my default folders. Figured I had a Registry problem. Deleted 97 and then Went into Registry and renamed all the folders in Office to OLD. This allowed ...

need clip art of bulding blue prints drawings can anyone help
need clip art for bussiness card back ground Try the Office clipart. A couple came up that may be suitable. http://office.microsoft.com/clipart/default.aspx?lc=en-us Input blueprint into the search. -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.microsoft.com "pelone" <pelone@discussions.microsoft.com> wrote in message news:B672EF98-E691-44A1-9085-821F760B2A61@microsoft.com... > need clip art for bussiness card back ground ...

Can Excel do this?
I am using Excel 2007. I am wanting to plot data for categories in a certain dept such as plumbing. I have about 10 different categories for which I plot out data for "year to date" and "week to date". "week to date" data is in a different section from "year to date" data. Obviously, the data sorted for "week to date" will be different for the "year to date" data. How can you get Excel to retrieve data from cells for a category like "toilets" so I can plot the data on one graph.. Example: Toilets, "week to date"...

Can't see my objects
I know this is a crazy question but I have a database that when I hold down the shift key and open it, I can't see my tables, queries, etc. I've never experienced this before. Any suggestions? Chris If the database designer didn't want you to see the database container, he can hide it. -- Arvin Meyer, MCP, MVP http://www.datastrat.com http://www.mvps.org/access http://www.accessmvp.com "Chris" <chriss@legendvalve.com> wrote in message news:O8iEV46dIHA.4696@TK2MSFTNGP05.phx.gbl... >I know this is a crazy question but I have a database that when I hold...

Can you track changes in Publisher as you can in Word?
I am editing a document for someone and I want to track the changes so they can identify where I have changed tham. How do I do this in Publisher? It isn't a Publisher feature. -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.microsoft.com "JoanD" <JoanD@discussions.microsoft.com> wrote in message news:FFD83A9C-611B-4210-BD70-34B370AC2E34@microsoft.com... >I am editing a document for someone and I want to track the changes so they > can identify where I have changed tham. How do I do this in Publisher? Would changin...

Where can we get xml scheme for tuning setting of WM2003/WM5.0 PDA
Hi all, We are working upon setting up a lot of WM2003/WM5.0 empowered mobile devices according with company standards. As far as I know these settings are tuned through xml file. Then this xml file has to be deployed deployed/executed onto mobile device. My question is where xml scheme for tuning such setting is published so we may assign necessary properties referencing it? Thank you in advance. ...

CRM Contacts not making to my Outlook Contacts Folder
I create a new crm contact in the web client. When I go to my SFO client and sync, the contact doesn't come over to my Outlook contacts eventhough I am the owner of the contact... Any suggestions? Bob Known Bug Bob. Hotfix to be released in May. Bill >-----Original Message----- >I create a new crm contact in the web client. > >When I go to my SFO client and sync, the contact doesn't >come over to my Outlook contacts eventhough I am the >owner of the contact... > >Any suggestions? > >Bob >. > ...

Can't sort
Hello all I have a textbox on a form with the following control source: =DMax("[tblEmailLogs]![dteSend]","[tblEmailLogs]","[tblEmailLogs]![txtEmailT o] = [email] And ([tblEmailLogs]![txtSubject] Like ""*""&'pridoc'&""*"" or [tblEmailLogs]![txtSubject] Like ""*""&'electronic'&""*"")") The expression works fine, in that it gives the correct result every time, but I can't sort on it - the only right-click option that isn't greyed out...

I can write schema annotations but I can't read them...
I was wondering if anyone else had experienced a similar issue where it is possible to write xs:annotation elements to a schema (verified in the resulting document streamed to the filesystem) but I cannot read them when I System.Xml.Schema.Read() [static] the document back from the filesystem. It's like there not even there... but they are ?!? Rein A little more insight: I can read annotations with simple/sample schemas... the problem occurs with more elaborate schemas where the annotation is buried deep . Rein Rein, Can you post one of the schemas that you have problems with and y...

i am receiving error while downloading my emails but i can send #2
hello everyone, I have a question for you. I am not able to receive emials from our email server.but i can send the email successfully. Any i dea.? i am stuck here. Thanks for yr help. Thanks, Bharat. ...

how can I count hours more than 24?
Hi, I'm trying to sum time fields up so I could get the total time I've been working. The thing is that everytime the sum hits 24 hours it just goes to 0 again. This way I only get X*24 + showing hours and I have no idea what is total summ. So how should I format cells to make it show for example "94:30" or something similar Yours, Sirritys Sirritys Format as [hh]:mm Regards Trevor "Sirritys" <aki.koikkalainen@hotmail.com> wrote in message news:1160024631.843794.298440@h48g2000cwc.googlegroups.com... > Hi, > > I'm trying to sum time fie...

Making a graph with easily changed dates
My boss asked me to make a graph on one of his spreadsheets more user friendly...so that you could put a start and end date in two ajacent cells and the graph will automatically change to show the time between those dates. I didn't think it was going to be too hard but now i'm completely stumped...I've got the dates on the X-axis and 3 other lines that come from data on another sheet...and i can't even get the X-axis to easily adjust to two changeable dates (it will just show those two days rather than all the days inbetween).....if anyone has any suggestions i'd gre...

How can i get publisher to stop making shadows in my pictures?
I am trying to make a brochure that has floor plans on it. When it prints, it prints a shadows of the floor plans, making it hard to read! I've tried the shadow option and taking off the shadow and it doesn't work. On the screen the shadows aren't there. What is the deal?! Thanks for any help xaviermsu wrote: > I am trying to make a brochure that has floor plans on it. When it > prints, it prints a shadows of the floor plans, making it hard to > read! I've tried the shadow option and taking off the shadow and it > doesn't work. On the screen the shadows aren...

Can not insert data into List Control, why?
Hi all, I use the following code to insert columns and list data, I find the columns could be inserted successfully, but I can not see the inserted data, when I try to debug the progrm , I find the return iPos value is -1 LV_COLUMN lvc; lvc.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH | LVCF_FMT; lvc.fmt=LVCFMT_CENTER; lvc.iSubItem = 0; lvc.pszText = _T("PORT"); lvc.cx = 50; m_ctlProgressList.InsertColumn(1,&lvc); lvc.iSubItem = 1; lvc.pszText = _T("STATUS"); lvc.cx = 260; m_ctlProgressList.InsertColumn(2,&lvc); lv...

threadpool: how can I make sure just an X amount of threads (CPU's) are used?
Hi, I've made a test project to see how the CPU usage will react based on the example given on: http://msdn.microsoft.com/en-us/library/system.thread= ing.threadpool.queueuserworkitem(VS.71).aspx The code is below. What I want to achieve is to be able to make sure that for a number of task send to the threadpool (or any other solution), I will only use x number of CPU=92s. With the code below, it doesn=92t matter how I set ThreadPool.SetMaxThreads and ThreadPool.SetMinThreads, when I run the program, all my CPU=92s are consumed. I=92ve tested this on a computer with 2 and wit...