I am trying to create some kind of framework that simplifies process of writing object interaction algorithm. (One object -- many clients(algorithms))
For example I want to implement algorithm that do some very simple job and waits some condition meet in a loop:
public void MakeVerySimpleJob() { } public void AsyncLoop() { // real algorithm can be more complex, but job is always very simple while (true) { MakeVerySimpleJob(); WakeUpCondition = "As fast as u can!"; JobComplete.Set(); WakeUp.WaitOne(); } } void main() { Thread MyThread = new Thread(AsyncLoop); MyThread.Start(); var w = new System.Diagnostics.Stopwatch(); w.Start(); for (int i = 0; i < 100000; i++) { // waitin for thread JobComplete.WaitOne(); // ok we did it WakeUpCondition = null; WakeUp.Set(); } w.Stop(); } AutoResetEvent JobComplete = new AutoResetEvent(false); AutoResetEvent WakeUp = new AutoResetEvent(false);
Unfortunately it consumes about
500ms
to do 100000 simple jobs.Ok multithreading is not acceptable in my case, but I dont want to force users to write algorithms in this manner:
// invoke it again and again public void PseudoAsyncLoop() { if (CurrentState == 1) { MakeVerySimpleJob(); CurrentState = 2; return; } else is (CurrentState == some_sate) { } } int CurrentState = 0;
So i look at
Enumerators
. With Enumerators user can implement their own algorithm in traditional style:public IEnumerable<bool> PseudoAsyncLoop() { while (true) { MakeVerySimpleJob(); WakeUpCondition = "As fast as u can!"; yield return true; } } public string WakeUpCondition { get; private set; } void main() { var MyLoop = PseudoAsyncLoop(); var LoopEnumerator = MyLoop.GetEnumerator(); var w = new System.Diagnostics.Stopwatch(); w.Start(); for(int i = 0; i < 100000; i ++) { LoopEnumerator.MoveNext(); // ok we did it WakeUpCondition = null; } w.Stop(); }
Now it takes about
3ms
, great. But i think its something wrong with that all...
My questions is:
- Am I in right direction?
- How does professional programmers solves that types of problems?
- May be there is some ways to optimize multithreaded version?