forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiThreadRunner.cs
81 lines (73 loc) · 1.85 KB
/
MultiThreadRunner.cs
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
using System;
using System.Threading;
namespace NHibernate.Test
{
public class MultiThreadRunner<T>
{
public delegate void ExecuteAction(T subject);
private readonly int numThreads;
private readonly ExecuteAction[] actions;
private readonly Random rnd = new Random();
private bool running;
private int timeout = 1000;
private int timeoutBetweenThreadStart = 30;
public MultiThreadRunner(int numThreads, ExecuteAction[] actions)
{
if(numThreads < 1)
{
throw new ArgumentOutOfRangeException("numThreads",numThreads,"Must be GT 1");
}
if (actions == null || actions.Length == 0)
{
throw new ArgumentNullException("actions");
}
foreach (ExecuteAction action in actions)
{
if(action==null)
throw new ArgumentNullException("actions", "null delegate");
}
this.numThreads = numThreads;
this.actions = actions;
}
public int EndTimeout
{
get { return timeout; }
set { timeout = value; }
}
public int TimeoutBetweenThreadStart
{
get { return timeoutBetweenThreadStart; }
set { timeoutBetweenThreadStart = value; }
}
public void Run(T subjectInstance)
{
running = true;
Thread[] t = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
{
t[i] = new Thread(ThreadProc);
t[i].Name = i.ToString();
t[i].Start(subjectInstance);
if (i > 2)
Thread.Sleep(timeoutBetweenThreadStart);
}
Thread.Sleep(timeout);
// Tell the threads to shut down, then wait until they all
// finish.
running = false;
for (int i = 0; i < numThreads; i++)
{
t[i].Join();
}
}
private void ThreadProc(object arg)
{
T subjectInstance = (T) arg;
while (running)
{
int actionIdx = rnd.Next(0, actions.Length);
actions[actionIdx](subjectInstance);
}
}
}
}