1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| class Program
{
static int cthread = 64; // nombre de thread à lancer (entre 1 et 64)
static int endLoop = 1000000; // borne sup boucle.
class threadParam
{
public ManualResetEvent oEvent = null;
public bool useLock = false;
}
class threadContainer
{
private int yes = 0;
public int Yes
{
get { return yes; }
}
private object objLock = new object();
private void loop()
{
for (int j = 0; j < endLoop; j++)
{
yes++;
}
}
public void threadedMethod(object oparam)
{
threadParam param = oparam as threadParam;
if (param.useLock)
{
lock (objLock)
{
loop();
}
}
else
{
loop();
}
if (param.oEvent != null)
param.oEvent.Set();
}
}
private static int starter(bool thread, bool uselock)
{
threadContainer c = new threadContainer();
ManualResetEvent[] events = null;
if (thread)
{
events = new ManualResetEvent[cthread];
}
for (int j = 0; j < cthread; j++)
{
threadParam param = new threadParam();
if (thread)
{
events[j] = new ManualResetEvent(false);
param.oEvent = events[j];
param.useLock = uselock;
Thread t = new Thread(c.threadedMethod);
t.Start(param);
}
else
{
c.threadedMethod(param);
}
}
if (thread)
{
WaitHandle.WaitAll(events);
}
return c.Yes;
}
static void writeResult(string text, int val, int expectedVal)
{
Console.WriteLine(text + " {0} => {1}", val, val == expectedVal ? "OK" : "Nawak !");
}
static void Main(string[] args)
{
int expectedVal = cthread * endLoop;
Console.WriteLine("Valeur attendue : {0}", expectedVal ); // result ok
int v = starter(false, false);
writeResult("Terminé sans thread", v, expectedVal);
v = starter(true, false);
writeResult("Terminé sans lock", v, expectedVal);
v = starter(true, true);
writeResult("Terminé avec lock", v, expectedVal);
Console.ReadKey();
}
} |
Partager