Reputation: 573
public delegate bool FunctieCompara(int a, int b); this is the delegate
Simple function calls:
TyG.bubbleSort(TyG.max, TyG.Lungime, TyG.Secv);
TyG.bubbleSort(TyG.min, TyG.Lungime, TyG.secvMin);
I have a Class Sorts
and in this class I have a lot of methods like
public void bubbleSort(functionDelegate f, int n, int [] v)
and much more sorts but with this parameters. In other class I have a instance of
Sortst tyg = new Sorts()
I want to create a thread
Thread Thr = new Thread(new ThreadStart(tyg.bubbleSort(functionDelegate)))
I didn't figure it out this thing works in my case, how can i use thread with a method that use a delegate, in my case the delegate is a max/min
for comparing numbers for doing sorts in place in v[]
. I want to make 2 threads for doing the both sorts bubbleSort(max, n, v)
and bubbleSort(min, n, v)
same time. That is what thread does anyway, anyhow can anyone help me a little please?
Upvotes: 3
Views: 2163
Reputation: 62439
Do you mean like this?
var t1 = new Thread(
o =>
{
tyg.bubbleSort(max, n, v1);
});
var t2 = new Thread(
o =>
{
tyg.bubbleSort(min, n, v2);
});
t1.Start(); // start threads
t2.Start();
t1.Join(); // wait for both threads to finish
t2.Join();
Note that if you are sorting in place you should use different arrays (v1
and v2
) because otherwise the threads will be overwriting the same array.
If you are interested, also look over the Task
construct of .NET 4.0.
Alternatively, if you want to be cool (.NET 4.0+):
Parallel.Invoke(
() => tyg.bubbleSort(max, n, v1),
() => tyg.bubbleSort(min, n, v2));
Upvotes: 4
Reputation: 62494
Using .NET Framework 4 and Task Parallel Library:
var factory = new TaskFactory(TaskCreationOptions.None,
TaskContinuationOptions.None);
var sorts = new Sorts();
FunctieCompara greaterThanComparer = (a, b) => { return a > b; };
FunctieCompara lessThanComparer = (a, b) => { return a < b; };
var sorterWorkers = new Task[]
{
factory.StartNew(() => sorts.BubbleSort(greaterThanComparer, 0, new int[] {})),
factory.StartNew(() => sorts.BubbleSort(lessThanComparer, 0, new int[] {}))
};
Task.WaitAll(sorterWorkers);
Upvotes: 2