// $Id$ // // Copyright 2007-2008 Cisco Systems Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. using System; using System.Runtime.CompilerServices; using System.Threading; namespace Etch.Support { /// /// A free implementation of pool /// public class FreePool : Pool { /// /// Constructs a FreePool with specified maxSize. /// /// maximum number of free threads at one time /// after which reject requests. public FreePool( int maxSize ) { this.maxSize = maxSize; myThreads = new Thread[ maxSize ]; } /// /// Constructs a FreePool with maxSize 50 /// public FreePool() : this( 50 ) { } private int maxSize; private int currentThreads = 0; Thread[] myThreads; void Run() { //donothing } private Boolean open = true; /// /// Closes the pool. This just marks the pool as being closed, it doesn't /// actually do anything to the currently running thread. But no more /// threads are allowed to start. /// public void Close() { open = false; } /// /// Joins each of the threads in this pool until there /// are none left. The pool will be closed first. /// Exception: /// throws ThreadInterruptedException /// public void Join() { Close(); for ( int i = 0; i < currentThreads; i++ ) { if ( myThreads[ i ].IsAlive ) myThreads[ i ].Join(); } } /// /// Finds the number of active threads in this pool /// /// the number of active threads public int ActiveCount() { int count = 0; for ( int i = 0; i < currentThreads; i++ ) { if ( myThreads[ i ].IsAlive ) count++; } return count; } #region Pool Members [MethodImpl( MethodImplOptions.Synchronized )] public void Run( RunDelegate d1, ExceptionDelegate d2 ) { if ( !open || ActiveCount() >= maxSize ) throw new Exception( "free pool thread count exceeded or pool closed" ); myThreads[ currentThreads ] = new Thread( new ThreadStart( delegate() { try { d1(); } catch ( Exception e ) { d2( e ); } } ) ); myThreads[ currentThreads ].Start(); currentThreads++; } #endregion } }