I am new to flows, and I was wondering how to use them for evaluation in a non-deterministic state machine.
I have a method that calls another method:
public bool Evaluate2(string s) { accepted = false; ThreadEval(s, StartState); return accepted; }
variable accepted is a member of the class, and I use it to control when other threads should stop.
void ThreadEval(string s, State q) { if (s.Length == 0 && q.IsFinal) { accepted = true; return; } bool found = true; State current = q; for (int i = 0; found && !accepted && i < s.Length; i++) { found = false; foreach (Transition t in current.transitions) if (t.symbol == s[i]) { Thread thread = new Thread(new ThreadStart(delegate { ThreadEval(s.Substring(i+1), t.to); })); thread.Start(); found = true; } } }
Each of my states has a set of transitions. A transition consists of a symbol and the state in which it can go, consuming this symbol. Therefore, if I find a possible transition, I want to create a new thread and examine the rest of the line (without the current character) ...
I currently have 2 problems:
A “return accepted” is executed before all threads created inside the ThreadEval have completed them. Is there a way to ensure that it does not return until those threads run out? I put Thread.Sleep (200) before returning, and it worked, but 200 ms may not be enough for large lines, and I also do not want to increase the value, so small lines will take longer than they need to be processed.
The code, as it was, leads to some indexing exception ... I'm 99.999% sure that it is true as it is, but it will only stop crashing if I call a substring that passes the value i instead of i + 1 ... but if I call only with i , it will never reach the end of the line, and depending on the configuration of the machine, it can lead to an infinite loop. I don’t know exactly how streams work, but I suspect that maybe some kind of parallel processing changes the value of i before cutting the substring. How can I assure that whenever I call a new thread, I only drop the current char?
If anyone has suggestions for using threads with more elegance, I would be grateful until the only way I found to pass parameters to the function that the thread was assigned to is to use a delegate.
source share