I'm doing some college work and I'm supposed to simulate 10, 100, 1,000 and 10,000 threads doing 1,000,000 locks and unlocks in a mutex (static Mutex m_mutex = new Mutex();
) and in a semaphore as mutex (static SemaphoreSlim m_semaphore = new SemaphoreSlim(1);
, correct?).
I'm having no trouble in the first three cases, but I got a Memory Exception in the 10,000 threads case. My code:
resultados.WriteLine("=== 10 threads ===");
ts = new TimeSpan();
media = 0;
parcial = 0;
resultados.WriteLine("Parciais:");
for (int i = 0; i < 10; i++)
{
parcial = LockAndUnlock_Semaphore_ComDisputa(10);
media += parcial;
ts = TimeSpan.FromTicks(parcial);
resultados.WriteLine(ts.ToString());
}
ts = TimeSpan.FromTicks(media / 10);
resultados.WriteLine("Média: " + ts.ToString());
I'm supposed to take 10 tests and measure the average.
private static long LockAndUnlock_Semaphore_ComDisputa(int numeroDeThreads)
{
Thread[] threads10 = new Thread[10];
Thread[] threads100 = new Thread[100];
Thread[] threads1000 = new Thread[1000];
Thread[] threads10000 = new Thread[10000];
//switch in the numeroDeThreads var
//[...]
case 10000:
sw.Start();
for (int i = 0; i < numeroDeThreads; i++)
{
threads10000[i] = new Thread(LockUnlockSemaphore);
threads10000[i].Priority = ThreadPriority.Highest;
threads10000[i].Start();
}
for (int i = 0; i < numeroDeThreads; i++)
{
threads10000[i].Join();
}
sw.Stop();
break;
//[...]
return sw.ElapsedTicks;
static void LockUnlockSemaphore()
{
for (int i = 0; i < 1000000; i++)
{
m_semaphore.Wait();
//thread dentro do semaforo
m_semaphore.Release();
}
}
While I post this question, I'm trying again but this this I create the thread vector like this:
Thread[] threads = new Thread[numeroDeThreads];
I'm supposed to test in mutex and in semaphore as mutex, but the error happen in the just mutex.
EDIT
Even with the Thread[] threads = new Thread[numeroDeThreads]; I got outofmemoryexception =( ...
Thanks in advance,
Pedro Dusso