Search Results

Search found 215 results on 9 pages for 'threadpool'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Query on simple C++ threadpool implementation

    - by ticketman
    Stackoverflow has been a tremendous help to me and I'd to give something back to the community. I have been implementing a simple threadpool using the tinythread C++ portable thread library, using what I have learnt from Stackoverflow. I am new to thread programming, so not that comfortable with mutexes, etc. I have a question best asked after presenting the code (which runs quite well under Linux): // ThreadPool.h class ThreadPool { public: ThreadPool(); ~ThreadPool(); // Creates a pool of threads and gets them ready to be used void CreateThreads(int numOfThreads); // Assigns a job to a thread in the pool, but doesn't start the job // Each SubmitJob call will use up one thread of the pool. // This operation can only be undone by calling StartJobs and // then waiting for the jobs to complete. On completion, // new jobs may be submitted. void SubmitJob( void (*workFunc)(void *), void *workData ); // Begins execution of all the jobs in the pool. void StartJobs(); // Waits until all jobs have completed. // The wait will block the caller. // On completion, new jobs may be submitted. void WaitForJobsToComplete(); private: enum typeOfWorkEnum { e_work, e_quit }; class ThreadData { public: bool ready; // thread has been created and is ready for work bool haveWorkToDo; typeOfWorkEnum typeOfWork; // Pointer to the work function each thread has to call. void (*workFunc)(void *); // Pointer to work data void *workData; ThreadData() : ready(false), haveWorkToDo(false) { }; }; struct ThreadArgStruct { ThreadPool *threadPoolInstance; int threadId; }; // Data for each thread ThreadData *m_ThreadData; ThreadPool(ThreadPool const&); // copy ctor hidden ThreadPool& operator=(ThreadPool const&); // assign op. hidden // Static function that provides the function pointer that a thread can call // By including the ThreadPool instance in the void * parameter, // we can use it to access other data and methods in the ThreadPool instance. static void ThreadFuncWrapper(void *arg) { ThreadArgStruct *threadArg = static_cast<ThreadArgStruct *>(arg); threadArg->threadPoolInstance->ThreadFunc(threadArg->threadId); } // The function each thread calls void ThreadFunc( int threadId ); // Called by the thread pool destructor void DestroyThreadPool(); // Total number of threads available // (fixed on creation of thread pool) int m_numOfThreads; int m_NumOfThreadsDoingWork; int m_NumOfThreadsGivenJobs; // List of threads std::vector<tthread::thread *> m_ThreadList; // Condition variable to signal each thread has been created and executing tthread::mutex m_ThreadReady_mutex; tthread::condition_variable m_ThreadReady_condvar; // Condition variable to signal each thread to start work tthread::mutex m_WorkToDo_mutex; tthread::condition_variable m_WorkToDo_condvar; // Condition variable to signal the main thread that // all threads in the pool have completed their work tthread::mutex m_WorkCompleted_mutex; tthread::condition_variable m_WorkCompleted_condvar; }; cpp file: // // ThreadPool.cpp // #include "ThreadPool.h" // This is the thread function for each thread. // All threads remain in this function until // they are asked to quit, which only happens // when terminating the thread pool. void ThreadPool::ThreadFunc( int threadId ) { ThreadData *myThreadData = &m_ThreadData[threadId]; std::cout << "Hello world: Thread " << threadId << std::endl; // Signal that this thread is ready m_ThreadReady_mutex.lock(); myThreadData->ready = true; m_ThreadReady_condvar.notify_one(); // notify the main thread m_ThreadReady_mutex.unlock(); while(true) { //tthread::lock_guard<tthread::mutex> guard(m); m_WorkToDo_mutex.lock(); while(!myThreadData->haveWorkToDo) // check for work to do m_WorkToDo_condvar.wait(m_WorkToDo_mutex); // if no work, wait here myThreadData->haveWorkToDo = false; // need to do this before unlocking the mutex m_WorkToDo_mutex.unlock(); // Do the work switch(myThreadData->typeOfWork) { case e_work: std::cout << "Thread " << threadId << ": Woken with work to do\n"; // Do work myThreadData->workFunc(myThreadData->workData); std::cout << "#Thread " << threadId << ": Work is completed\n"; break; case e_quit: std::cout << "Thread " << threadId << ": Asked to quit\n"; return; // ends the thread } // Now to signal the main thread that my work is completed m_WorkCompleted_mutex.lock(); m_NumOfThreadsDoingWork--; // Unsure if this 'if' would make the program more efficient // if(NumOfThreadsDoingWork == 0) m_WorkCompleted_condvar.notify_one(); // notify the main thread m_WorkCompleted_mutex.unlock(); } } ThreadPool::ThreadPool() { m_numOfThreads = 0; m_NumOfThreadsDoingWork = 0; m_NumOfThreadsGivenJobs = 0; } ThreadPool::~ThreadPool() { if(m_numOfThreads) { DestroyThreadPool(); delete [] m_ThreadData; } } void ThreadPool::CreateThreads(int numOfThreads) { // Check a thread pool has already been created if(m_numOfThreads > 0) return; m_NumOfThreadsGivenJobs = 0; m_NumOfThreadsDoingWork = 0; m_numOfThreads = numOfThreads; m_ThreadData = new ThreadData[m_numOfThreads]; ThreadArgStruct threadArg; for(int i=0; i<m_numOfThreads; ++i) { threadArg.threadId = i; threadArg.threadPoolInstance = this; // Creates the thread and save in a list so we can destroy it later m_ThreadList.push_back( new tthread::thread( ThreadFuncWrapper, (void *)&threadArg ) ); // It takes a little time for a thread to get established. // Best wait until it gets established before creating the next thread. m_ThreadReady_mutex.lock(); while(!m_ThreadData[i].ready) // Check if thread is ready m_ThreadReady_condvar.wait(m_ThreadReady_mutex); // If not, wait here m_ThreadReady_mutex.unlock(); } } // Adds a job to the batch, but doesn't start the job void ThreadPool::SubmitJob(void (*workFunc)(void *), void *workData) { // Check that the thread pool has been created if(!m_numOfThreads) return; if(m_NumOfThreadsGivenJobs >= m_numOfThreads) return; m_ThreadData[m_NumOfThreadsGivenJobs].workFunc = workFunc; m_ThreadData[m_NumOfThreadsGivenJobs].workData = workData; std::cout << "Submitted job " << m_NumOfThreadsGivenJobs << std::endl; m_NumOfThreadsGivenJobs++; } void ThreadPool::StartJobs() { // Check that the thread pool has been created // and some jobs have been assigned if(!m_numOfThreads || !m_NumOfThreadsGivenJobs) return; // Set 'haveworkToDo' flag for all threads m_WorkToDo_mutex.lock(); for(int i=0; i<m_NumOfThreadsGivenJobs; ++i) m_ThreadData[i].haveWorkToDo = true; m_NumOfThreadsDoingWork = m_NumOfThreadsGivenJobs; // Reset this counter so we can resubmit jobs later m_NumOfThreadsGivenJobs = 0; // Notify all threads they have work to do m_WorkToDo_condvar.notify_all(); m_WorkToDo_mutex.unlock(); } void ThreadPool::WaitForJobsToComplete() { // Check that a thread pool has been created if(!m_numOfThreads) return; m_WorkCompleted_mutex.lock(); while(m_NumOfThreadsDoingWork > 0) // Check if all threads have completed their work m_WorkCompleted_condvar.wait(m_WorkCompleted_mutex); // If not, wait here m_WorkCompleted_mutex.unlock(); } void ThreadPool::DestroyThreadPool() { std::cout << "Ask threads to quit\n"; m_WorkToDo_mutex.lock(); for(int i=0; i<m_numOfThreads; ++i) { m_ThreadData[i].haveWorkToDo = true; m_ThreadData[i].typeOfWork = e_quit; } m_WorkToDo_condvar.notify_all(); m_WorkToDo_mutex.unlock(); // As each thread terminates, catch them here for(int i=0; i<m_numOfThreads; ++i) { tthread::thread *t = m_ThreadList[i]; // Wait for thread to complete t->join(); } m_numOfThreads = 0; } Example of usage: (this calculates pi-squared/6) struct CalculationDataStruct { int inputVal; double outputVal; }; void LongCalculation( void *theSums ) { CalculationDataStruct *sums = (CalculationDataStruct *)theSums; int terms = sums->inputVal; double sum; for(int i=1; i<terms; i++) sum += 1.0/( double(i)*double(i) ); sums->outputVal = sum; } int main(int argc, char** argv) { int numThreads = 10; // Create pool ThreadPool threadPool; threadPool.CreateThreads(numThreads); // Create thread workspace CalculationDataStruct sums[numThreads]; // Set up jobs for(int i=0; i<numThreads; i++) { sums[i].inputVal = 3000*(i+1); threadPool.SubmitJob(LongCalculation, &sums[i]); } // Run the jobs threadPool.StartJobs(); threadPool.WaitForJobsToComplete(); // Print results for(int i=0; i<numThreads; i++) std::cout << "Sum of " << sums[i].inputVal << " terms is " << sums[i].outputVal << std::endl; return 0; } Question: In the ThreadPool::ThreadFunc method, would better performance be obtained if the following if statement if(NumOfThreadsDoingWork == 0) was included? Also, I'd be grateful of criticisms and ways to improve the code. At the same time, I hope the code is of use to others.

    Read the article

  • Can I partition the C# System.Threading.ThreadPool?

    - by Drew Shafer
    I love ThreadPool. It makes my life better. However, my love may have quietly turned into an abusive relationship that I need to escape from, so I need some advice from my SO brothers (and presumably sisters, although I haven't seen any actual evidence of that yet). My basic problem is that I have several different libraries that are all using the threadpool in an uncoordinated way, and running out of threads is a possibility. I was hoping there was some way I could partition the ThreadPool up so I could give a certain class 1 thread, another 20 threads, another 5 threads, and so on. I know I could write my own ThreadPool implementation. I don't want to do that, because I'm lazy. So, is there a simple solution already out there? Currently I'm constrained to using the 3.5 CLR. I know a lot of this stuff becomes easier in 4.0.

    Read the article

  • ASP.NET CacheDependency out of ThreadPool

    - by Stephen
    In an async http handler, we add items to the ASP.NET cache, with dependencies on some files. If the async method executes on a thread from the ThreadPool, all is fine: AsyncResult result = new AsyncResult(context, cb, extraData); ThreadPool.QueueUserWorkItem(new WaitCallBack(DoProcessRequest), result); But as soon as we try to execute on a thread out of the ThreadPool: AsyncResult result = new AsyncResult(context, cb, extraData); Runner runner = new Runner(result); Thread thread = new Thread(new ThreadStart(runner.Run()); ... where Runner.Run just invokes DoProcessRequest, The dependencies do trigger right after the thread exits. I.e. the items are immediately removed from the cache, the reason being the dependencies. We want to use an out-of-pool thread because the processing might take a long time. So obviously something's missing when we create the thread. We might need to propagate the call context, the http context... Has anybody already encountered that issue? Note: off-the-shelf custom threadpools probably solve this. Writing our own threadpool is probably a bad idea (think NIH syndrom). Yet I'd like to understand this in details, though.

    Read the article

  • Need help understanding .net ThreadPool

    - by Meredith
    I am trying to understand what ThreadPool does, I have this .NET example: class Program { static void Main() { int c = 2; // Use AutoResetEvent for thread management AutoResetEvent[] arr = new AutoResetEvent[50]; for (int i = 0; i < arr.Length; ++i) { arr[i] = new AutoResetEvent(false); } // Set the number of minimum threads ThreadPool.SetMinThreads(c, 4); // Enqueue 50 work items that run the code in this delegate function for (int i = 0; i < arr.Length; i++) { ThreadPool.QueueUserWorkItem(delegate(object o) { Thread.Sleep(100); arr[(int)o].Set(); // Signals completion }, i); } // Wait for all tasks to complete WaitHandle.WaitAll(arr); } } Does this run 50 "tasks", in groups of 2 (int c) until they all finish? Or I am not understanding what it really does.

    Read the article

  • Using SqlBulkCopy in a multithread scenario with ThreadPool issue

    - by Ruben F.
    Hi. I'm facing a dilemma (!). In a first scenario, i implemented a solution that replicates data from one data base to another using SQLBulkCopy synchronously and i had no problem at all. Now, using ThreadPool, i implemented the same in a assynchronously scenario, a thread per table, and all works fine, but past some time (usualy 1hour because the operations of copy takes about the same time), the operations sended to the ThreadPool stop being executed. There are one diferent SQLBulkCopy using one diferent SQLConnection per thread. I already see the number of free threads, and they are all free at the begining of the invocation...I have one AutoResetEvent to wait that the threads finish their job before launching again, and a Semaphore FIFO that hold the counter of active threads. There are some issue that I have forgotten or that I should avaliate when using SqlBulkCopy? I apreciate some help, because my ideas are over;) Thanks

    Read the article

  • Thread vs ThreadPool - .Net 2.0

    - by NLV
    Hello I'm not able to understand the difference between Thread vs ThreadPool. Consider i've to manipulate 50,000 records using threads. In case of threads i need to either predefine no of threads or no of records per threads. Either of them has to be constant. In case of threadpool we dont need to set any of them theoretically. But practically we need to assign the number of records per thread, because the no of threads may grow extremely large if the input no of records is huge. Any insights on this?

    Read the article

  • C# Execute Method (with Parameters) with ThreadPool

    - by washtik
    We have the following piece of code (idea for this code was found on this website) which will spawn new threads for the method "Do_SomeWork()". This enables us to run the method multiple times asynchronously. The code is: var numThreads = 20; var toProcess = numThreads; var resetEvent = new ManualResetEvent(false); for (var i = 0; i < numThreads; i++) { new Thread(delegate() { Do_SomeWork(Parameter1, Parameter2, Parameter3); if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set(); }).Start(); } resetEvent.WaitOne(); However we would like to make use of ThreadPool rather than create our own new threads which can be detrimental to performance. The question is how can we modify the above code to make use of ThreadPool keeping in mind that the method "Do_SomeWork" takes multiple parameters and also has a return type (i.e. method is not void). Also, this is C# 2.0.

    Read the article

  • Threadpool design question

    - by ZeroVector
    I have a design question. I want some feedback to know if a ThreadPool is appropriate for the client program I am writing. I am having a client running as a service processing database records. Each of these records contains connection information to external FTP sites [basically it is a queue of files to transfer]. A lot of them are to the same host, just moving different files. Therefore, I am grouping them together by host. I want to be able to create a new thread per host. I really don't care when the transfers finish, they just need to do all the work (or try to do) they were assigned, and then terminate once they are finished, cleaning up all resources they used in the process. I anticipate no more than 10-25 connections to be established. Once the transfer queue is empty, the program will simply wait until there are records in the queue again. Is the ThreadPool a good candidate for this or should I use a different approach? Edit: For the most part, this is the only significant custom application running on the server.

    Read the article

  • Wait until all threads teminated in ThreadPool

    - by Neir0
    Hi i have this code: var list = new List<int>(); for(int i=0;i<10;i++) list.Add(i); for(int i=0;i<10;i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(x => { Console.WriteLine(x); }),list[i]); } And i want to know when all threadpools threads finished their work. How i can to do that?

    Read the article

  • TaskFactory.StartNew versus ThreadPool.QueueUserWorkItem

    - by Dan Tao
    Apparently the TaskFactory.StartNew method in .NET 4.0 is intended as a replacement for ThreadPool.QueueUserWorkItem (according to this post, anyway). My question is simple: does anyone know why? Does TaskFactory.StartNew have better performance? Does it use less memory? Or is it mainly for the additional functionality provided by the Task class? In the latter case, does StartNew possibly have worse performance than QueueUserWorkItem? It seems to me that StartNew would actually potentially use more memory than QueueUserWorkItem, since it returns a Task object with every call and I would expect that to result in more memory allocation. In any case, I'm interested to know which is more appropriate for a high-performance scenario.

    Read the article

  • .NET ThreadPool QueueUserWorkItem Synchronization

    - by ikurtz
    I am employing ThreadPool.QueueUserWorkItem to play some sound files and not hanging up the GUI while doing so. It is working but has an undesirable side effect. While the QueueUserWorkItem CallBack Proc is being executed there is nothing to stop it from starting a new thread. This causes the samples in the threads to overlap. How can I make it so that it waits for the already running thread to finish running and only then run the next request? EDIT: I did: Thread t = new Thread(FireAttackProc(fireResult)); t.Start(); but it gave me some errors. How do I specify a thread method with parameters?

    Read the article

  • Add multiples Picturebox using ThreadPool

    - by Pmdusso
    Hi! Im doing a Naval Battle for University. I decided to do it in C#. My board is 20 x 20 of mini (20x20) PictureBoxes. The problem is when I load the board I got a huuuge delay for draw all of them in the panel which contains them. So I thought to ThreadPool my method to escale the picuteres boxes creation and drawing fester. Is this the correct aproach? I'm wondering if even if I launch 20 threads to create and set the picturesoboxes together I will still have the graphic delay. (I wont past code right now because maybe the answer independs of it... if not, I past next :) Sorry the bad english, Thanks folks!

    Read the article

  • Port scanning using threadpool

    - by thenry
    I am trying to run a small app that scans ports and checks to see if they are open using and practicing with threadpools. The console window will ask a number and scans ports from 1 to X and will display each port whether they are open or closed. My problem is that as it goes through each port, it sometimes stops prematurely. It doesn't stop at just one number either, its pretty random. For example it I specify 200. The console will scroll through each port then stops at 110. Next time I run it, it stops at 80. Code Left out some of the things, assume all variables are declared where they should. First part is in Main. static void Main(string[] args) { string portNum; int convertedNum; Console.WriteLine("Scanning ports 1-X"); portNum = Console.ReadLine(); convertedNum = Convert.ToInt32(portNum); try { for (int i = 1; i <= convertedNum; i++) { ThreadPool.QueueUserWorkItem(scanPort, i); Thread.Sleep(100); } } catch (Exception e) { Console.WriteLine("exception " + e); } } static void scanPort(object o) { TcpClient scanner = new TcpClient(); try { scanner.Connect("127.0.0.1",(int)o); Console.WriteLine("Port {0} open", o); } catch { Console.WriteLine("Port {0} closed",o); } } }

    Read the article

  • How to log correct context with Threadpool threads using log4net?

    - by myotherme
    I am trying to find a way to log useful context from a bunch of threads. The problem is that a lot of code is dealt with on Events that are arriving via threadpool threads (as far as I can tell) so their names are not in relation to any context. The problem can be demonstrated with the following code: class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { new Thread(TestThis).Start("ThreadA"); new Thread(TestThis).Start("ThreadB"); Console.ReadLine(); } private static void TestThis(object name) { var nameStr = (string)name; Thread.CurrentThread.Name = nameStr; log4net.ThreadContext.Properties["ThreadContext"] = nameStr; log4net.LogicalThreadContext.Properties["LogicalThreadContext"] = nameStr; log.Debug("From Thread itself"); ThreadPool.QueueUserWorkItem(x => log.Debug("From threadpool Thread: " + nameStr)); } } The Conversion pattern is: %date [%thread] %-5level %logger [%property] - %message%newline The output is like so: 2010-05-21 15:08:02,357 [ThreadA] DEBUG LogicalContextTest.Program [{LogicalThreadContext=ThreadA, log4net:HostName=xxx, ThreadContext=ThreadA}] - From Thread itself 2010-05-21 15:08:02,357 [ThreadB] DEBUG LogicalContextTest.Program [{LogicalThreadContext=ThreadB, log4net:HostName=xxx, ThreadContext=ThreadB}] - From Thread itself 2010-05-21 15:08:02,404 [7] DEBUG LogicalContextTest.Program [{log4net:HostName=xxx}] - From threadpool Thread: ThreadA 2010-05-21 15:08:02,420 [16] DEBUG LogicalContextTest.Program [{log4net:HostName=xxx}] - From threadpool Thread: ThreadB As you can see the last two rows have no Names of useful information to distinguish the 2 threads, other than manually adding the name to the message (which I want to avoid). How can I get the Name/Context into the log for the threadpool threads without adding it to the message at every call?

    Read the article

  • CAsyncSocket and ThreadPool problem

    - by zabulus
    I have a server application with such structure: There is one object, call him Server, that in endless cycle listens and accepts connections. I have descendant class from CAsyncSocket, that has overriden event OnReceive, call him ProxySocket. Also I have a thread pool with early created threads. When connection is received by server object he accepts the new connection on the new object ProxySocket. When data arrives to the ProxySocket, he creates a command object and gives it to thread pool. In this command object I giving the socket handle of a ProxySocket. When new object of command is creating - I creating a new Socket in working thread and attach handle to it. My issue is next: When command ends, socket doesn't close, I just detach handle it and set CSocket handle to INVALID_SOCKET value, as planned. But my first ProxySocket object doesn't receives messages of new data receiving after that. How can I solve this?

    Read the article

  • Wait for tasks to get completed in threadpool.

    - by Alien01
    Hello I have created a thread pool in C++ which stores all tasks in a queue. Thread pool start n number of threads which takes tasks from queue , process each task and then delete tasks from queue. Now , I want to wait till all tasks get completed. Checking for empty queue for completion of tasks may not work as , task can be given to each thread and queue can be emptied but still the tasks can in processing mode. I am not getting idea how to wait for all the tasks completion.This is a design problem. Any suggestions?

    Read the article

  • Threadpool with pasistant worker instances

    - by Matt Smokey-waters Holmes
    So basically what im trying to do is queue up tasks in a thread pool to be executed as soon as a worker becomes free, i have found various examples of this but in all cases the examples have been setup to use a new Worker instance for each job, i want persistent workers. Im trying to make a ftp backup tool, i have it working but because of the limitations of a single connection it is slow. What i ideally want to do is have a single connection for scanning directories and building up a file list then four workers to download said files. Here is an example of my worker /** * FTP Worker */ public class Worker implements Runnable { protected FTPClient _ftp; // Connection details protected String _host = ""; protected String _user = ""; protected String _pass = ""; // worker status protected boolean _working = false; public Worker(String host, String user, String pass) { this._host = host; this._user = user; this._pass = pass; } // Check if the worker is in use public boolean inUse() { return this._working; } @Override public void run() { this._ftp = new FTPClient(); this._connect(); } // Download a file from the ftp server public boolean download(String base, String path, String file) { this._working = true; boolean outcome = true; //create directory if not exists File pathDir = new File(base + path); if (!pathDir.exists()) { pathDir.mkdirs(); } //download file try { OutputStream output = new FileOutputStream(base + path + file); this._ftp.retrieveFile(file, output); output.close(); } catch (Exception e) { outcome = false; } finally { this._working = false; return outcome; } } // Connect to the server protected boolean _connect() { try { this._ftp.connect(this._host); this._ftp.login(this._user, this._pass); } catch (Exception e) { return false; } return this._ftp.isConnected(); } // Disconnect from the server protected void _disconnect() { try { this._ftp.disconnect(); } catch (Exception e) { /* do nothing */ } } } and basically i want to be able to call Worker.download(...) for each task in a queue whenever a worker becomes available without having to create a new connection to the ftp server for each download Any help would be appreciated as iv'e never used threads before and I'm going round in circles at the moment

    Read the article

  • Waiting for a subset of threads in a Java ThreadPool

    - by David Semeria
    Let's say I have a thread pool containing X items, and a given task employs Y of these items (where Y is much smaller than X). I want to wait for all of the threads of a given task (Y items) to finish, not the entire thread pool. If the thread pool's execute() method returned a reference to the employed thread I could simply join() to each of these Y threads, but it doesn't. Does anyone know of an elegant way to accomplish this? Thanks.

    Read the article

  • Java ThreadPool for multiple identical tasks

    - by tdimmig
    I have 1 thread who sole job is to grab DatagramPackets off of a socket and stick them in a buffer. Another thread works out of that buffer, processing the DatagramPackets. I'd like to have a pool of threads working out of that buffer. I had thought to use a fixed thread pool to do this. To do so, do I need to create the pool, then submit enough runnables for execution to fill it up? I had hoped for a way to say "this is the thread/runnable that I want you to execute, this is how many I want running, GO!". Is there such a method of doing this? Is something other than a fixed thread pool better suited?

    Read the article

  • Does the number of busy worker threads in the CLR ThreadPool affect performance of I/O threads?

    - by andrej351
    We have a Windows Service which hosts a number of WCF services and, in an unrelated part of the app, makes extensive use of the TPL Task class to asynchronously do relatively short bits of work. It is my understanding that WCF uses managed I/O threads from the ThreadPool to execute requests. I noticed that after deploying a feature which significantly raised the applications use of Tasks, and as such the use of ThreadPool worker threads as well, performance of a couple of web services has become very slow. We're talking minutes instead of less than a second. The number of Tasks actually trying to run at any one time can range between 20 and 1000, which makes me think that any new (last in) work needing some CPU time could be forced to wait for quite some time. Does the (in my case extremely large) number of busy ThreadPool worker threads affect the ThreadPool's managed I/O threads? Or could these two be connected in any way? Thanks!

    Read the article

  • C# Is it possible to interrupt a specific thread inside a ThreadPool?

    - by Lirik
    Suppose that I've queued a work item in a ThreadPool, but the work item blocks if there is no data to process (reading from a BlockingQueue). If the queue is empty and there will be no more work going into the queue, then I must call the Thread.Interrupt method if I want to interrupt the blocking task, but how does one do the same thing with a ThreadPool? The code might look like this: void Run() { try { while(true) { blockingQueue.Dequeue(); doSomething(); } } finally { countDownLatch.Signal(); } } I'm aware that the best thing to do in this situation is use a regular Thread, but I'm wondering if there is a ThreadPool equivalent way to interrupt a work item.

    Read the article

  • Is this a good use for ThreadPool.QueueUserWorkItem?

    - by Matt Grande
    I have an application that, among other things, imports documents, then emails necessary parties to let them know that a document has been imported. It turns out that determining whom to email, then performing the emailing, is what's taking the longest. I was thinking of doing something like this: var document = ImportDocument(); ThreadPool.QueueUserWorkItem(s => SendEmail(document.Id)); return document; ... similar to DelayedJob in Rails, if that helps. Does that make sense in this context? What would you do?

    Read the article

  • Using ThreadPool.QueueUserWorkItem in ASP.NET in a high traffic scenario

    - by Michael Hart
    I've always been under the impression that using the ThreadPool for (let's say non-critical) short-lived background tasks was considered best practice, even in ASP.NET, but then I came across this article that seems to suggest otherwise - the argument being that you should leave the ThreadPool to deal with ASP.NET related requests. So here's how I've been doing small asynchronous tasks so far: ThreadPool.QueueUserWorkItem(s => PostLog(logEvent)) And the article is suggesting instead to create a thread explicitly, similar to: new Thread(() => PostLog(logEvent)){ IsBackground = true }.Start() The first method has the advantage of being managed and bounded, but there's the potential (if the article is correct) that the background tasks are then vying for threads with ASP.NET request-handlers. The second method frees up the ThreadPool, but at the cost of being unbounded and thus potentially using up too many resources. So my question is, is the advice in the article correct? If your site was getting so much traffic that your ThreadPool was getting full, then is it better to go out-of-band, or would a full ThreadPool imply that you're getting to the limit of your resources anyway, in which case you shouldn't be trying to start your own threads? Clarification: I'm just asking in the scope of small non-critical asynchronous tasks (eg, remote logging), not expensive work items that would require a separate process (in these cases I agree you'll need a more robust solution).

    Read the article

  • Jetty 6 - QueuedThreadPool versus ThreadPool

    - by Walter White
    Hi all, I am using Jetty 6 and was wondering when the QueuedThreadPool should be used over the ThreadPool? By default, Jetty 6 comes configured with the QueuedThreadPool. My server has Java 6 installed so I was thinking that I should use the ThreadPool: <New class="org.mortbay.thread.QueuedThreadPool"> <Set name="minThreads">10</Set> <Set name="maxThreads">200</Set> <Set name="lowThreads">20</Set> <Set name="SpawnOrShrinkAt">2</Set> </New> <New class="org.mortbay.thread.concurrent.ThreadPool"> <Set name="corePoolSize">50</Set> <Set name="maximumPoolSize">50</Set> </New> Thanks, Walter

    Read the article

  • C# Thread Queue Synchronize

    - by ikurtz
    Greetings, I am trying to play some audio files without holding up the GUI. Below is a sample of the code: if (audio) { if (ThreadPool.QueueUserWorkItem(new WaitCallback(CoordinateProc), fireResult)) { } else { MessageBox.Show("false"); } } if (audio) { if (ThreadPool.QueueUserWorkItem(new WaitCallback(FireProc), fireResult)) { } else { MessageBox.Show("false"); } } if (audio) { if (ThreadPool.QueueUserWorkItem(new WaitCallback(HitProc), fireResult)) { } else { MessageBox.Show("false"); } } The situation is the samples are not being played in order. some play before the other and I need to fix this so the samples are played one after another in order. How do I implement this please? Thank you.

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >