Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 10, 2014 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/da51a5f41cdc0ce828e9 to your computer and use it in GitHub Desktop.
Save Fhernd/da51a5f41cdc0ce828e9 to your computer and use it in GitHub Desktop.
Manejo de pool de threads con la clase Monitor.
using System;
using System.Threading;
namespace Recetas.CSharp.Cap04.R0407
{
public class BlogxCSw
{
// Representa el número de threads máximos
// soportados por el servidor:
private const int threads = 3;
// Representa la cantidad de usuarios que
// se van a conectar al blog:
private const int usuarios = 20;
// Representa el locker que se encarga de
// controlar el acceso al blog:
private static Object locker = new Object();
// Permite a un usuario ingresar al usuario:
public static void IngresarAlBlog()
{
while (true)
{
lock (locker)
{
Monitor.Wait (locker);
}
Console.WriteLine ("{0} accedió al Blog xCSw",
Thread.CurrentThread.Name
);
Thread.Sleep (150);
}
}
public static void Main()
{
// Creación del pool de threads:
Thread[] pool = new Thread[threads];
// Creación de cada uno de los threads:
for (int i = 0; i < threads; ++i)
{
pool[i] = new Thread (new ThreadStart (IngresarAlBlog));
pool[i].Name = String.Format ("Usuario {0}", (i + 1).ToString() );
pool[i].IsBackground = true;
pool[i].Start();
}
// Atienda las visitas al blog:
for (int i = 1; i <= usuarios; ++i)
{
Thread.Sleep (1000);
lock (locker)
{
Monitor.Pulse (locker);
}
}
Console.WriteLine ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment