Friday Programming Quiz [modified]
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
I'm not sure how well this would fit into your current implementation, but here is a small five minute solution that may work. I've not even tried to compile it though. Also, pick any container that will work better than
list
.class ActionList : public Action
{
public:
void Action( ActionComplete onComplete )
{
m_CurrentAct = m_Actions.begin();
m_CompleteFN = onComplete;(\*m\_CurrentAct).Action( actionCompleteInternal );
}
private:
void actionCompleteInternal()
{
++m_CurrentAct;
if( m_CurrentAct != m_Actions.end() )
{
(*m_CurrentAct).Action( actionCompleteInternal );
}
else
{
m_CompleteFN();
}
}ActionComplete m_CompleteFN;
std::list<Action*>::iterator m_CurrentAct;
std::list<Action*> m_Actions;
};ExecuteActions( action_list actions, onComplete )
{
list.Action( onComplete );
}Chris Richardson
-
I'm not sure how well this would fit into your current implementation, but here is a small five minute solution that may work. I've not even tried to compile it though. Also, pick any container that will work better than
list
.class ActionList : public Action
{
public:
void Action( ActionComplete onComplete )
{
m_CurrentAct = m_Actions.begin();
m_CompleteFN = onComplete;(\*m\_CurrentAct).Action( actionCompleteInternal );
}
private:
void actionCompleteInternal()
{
++m_CurrentAct;
if( m_CurrentAct != m_Actions.end() )
{
(*m_CurrentAct).Action( actionCompleteInternal );
}
else
{
m_CompleteFN();
}
}ActionComplete m_CompleteFN;
std::list<Action*>::iterator m_CurrentAct;
std::list<Action*> m_Actions;
};ExecuteActions( action_list actions, onComplete )
{
list.Action( onComplete );
}Chris Richardson
Yes that will work. But it can be further simplified if you are using JavaScript or LINQ.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Hi, what do you think of this solution?
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
for (int i = 0; i < actions.Length; i++)
{
ManualResetEvent mre = new ManualResetEvent(false);
actions[i](delegate() { mre.Set(); });
mre.WaitOne();
}
onAllActionsComplete();
}Robert
-
Hi, what do you think of this solution?
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
for (int i = 0; i < actions.Length; i++)
{
ManualResetEvent mre = new ManualResetEvent(false);
actions[i](delegate() { mre.Set(); });
mre.WaitOne();
}
onAllActionsComplete();
}Robert
:cool:This will work too. :) BTW: This is not really the most efficient thing to do but the point of this quiz is to have fun and not to develop an efficent solution.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
Hi, what do you think of this solution?
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
for (int i = 0; i < actions.Length; i++)
{
ManualResetEvent mre = new ManualResetEvent(false);
actions[i](delegate() { mre.Set(); });
mre.WaitOne();
}
onAllActionsComplete();
}Robert
Actually you can also do this:
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
AutoResetEvent are = new AutoResetEvent(false);
for (int i = 0; i < actions.Length; i++)
{
actions[i](delegate() { are.Set(); });
are.WaitOne();
}onAllActionsComplete();
}
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Hey, wait a minute! Isn't this a programming question?
Matt Gerrans
-
:cool:This will work too. :) BTW: This is not really the most efficient thing to do but the point of this quiz is to have fun and not to develop an efficent solution.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Now I'm curious. Why would you say that this isn't efficient? Robert
-
Hey, wait a minute! Isn't this a programming question?
Matt Gerrans
Matt Gerrans wrote:
Isn't this a programming question?
It's sorta - but it's a new tradition. Respect it or weep. :-D
Regards, Nish
Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
Currently working on C++/CLI in Action for Manning Publications. (*Sample chapter available online*) -
Hey, wait a minute! Isn't this a programming question?
Matt Gerrans
Matt Gerrans wrote:
Isn't this a programming question
This is a programming quiz. The purpose is to have fun. The problems presented here are too trivial.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Well I won't even try that one. And I wonder why you would insist that they be asynchronous if you only run one at a time, I'll assume they are from some other developer. Hmmm... I expect even if they are you could wrap them in something to make them appear synchronous. What I do have though is... In my current project I have need of putting data into a third-party product for which the only interface I have is a character-based program on a Unix server. I have to telnet to the Unix server, login, execute the program, put in the data, exit the program, logout, and disconnect. And I need to do this for each "item" I need to put into the system (trying to put in more than one per session is problematic). So I want to have multiple threads, each entering one item, and I don't want to proceed until they're all done. I accomplished this with what I call a ThreadStack (although it's technically neither LIFO nor FIFO). The code isn't yet ready for Code Project, but if anyone is interested I can clean it up. I'll mention that I've had this solution running as a Windows service with up to ten simultaneous threads for the past year with no problems.
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Funny, I have a very similar problem to solve, with regards to re-encoding a movie into a different format, that must first be indexed, then multiple threads can run to actually encode the movie in different speed formats, and when all the encoding is done, the database is notified that the entire process is complete. And to make matters more interesting, the threads have to be prioritized so that certain encodes are done first, and the system optimizes encoding by creating one thread per CPU. Anyways, I ended up using a priority queue to generate the task list and then a separate process pulls tasks off and assigns them to processors. When the task is complete, the thread notifies the queue processor that it can assign a new task. In your particular case, I'd probably just wire up an event to notify a worker thread that the task was done, set up and an index for the first task, do the task, increment, do the next task, etc., then call the actions complete event. Marc
People are just notoriously impossible. --DavidCrow
There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith -
Now I'm curious. Why would you say that this isn't efficient? Robert
Actually, efficent may have been a poor choice of word. I should have said not really the best solution. The problem is that one thread is used up by the wait handle and nothing can execute on that thread. For situations like ASP.NET where there are some set threads that work on request processing, a vital request processing thread will be used up just for waiting.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
Funny, I have a very similar problem to solve, with regards to re-encoding a movie into a different format, that must first be indexed, then multiple threads can run to actually encode the movie in different speed formats, and when all the encoding is done, the database is notified that the entire process is complete. And to make matters more interesting, the threads have to be prioritized so that certain encodes are done first, and the system optimizes encoding by creating one thread per CPU. Anyways, I ended up using a priority queue to generate the task list and then a separate process pulls tasks off and assigns them to processors. When the task is complete, the thread notifies the queue processor that it can assign a new task. In your particular case, I'd probably just wire up an event to notify a worker thread that the task was done, set up and an index for the first task, do the task, increment, do the next task, etc., then call the actions complete event. Marc
People are just notoriously impossible. --DavidCrow
There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh SmithActually my problem was in JavaScript/Ajax so I could not create threads. But it was fun to solve using anonymous functions and closures. PS I am sorry for hijacking the Friday Programming Quiz started by you.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
Actually, efficent may have been a poor choice of word. I should have said not really the best solution. The problem is that one thread is used up by the wait handle and nothing can execute on that thread. For situations like ASP.NET where there are some set threads that work on request processing, a vital request processing thread will be used up just for waiting.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Hi, if I understand you correctly one could overcome this problem by starting another thread where the waiting takes place. Thus the request processing thread won't be blocked. Nevertheless I agree that there is one thread more active than necessary. The best solution definitely depends on the context where the code is executed in. To be honest I also tried to just get the shortest solution I could think of. I think regarding this my code should be in the premier league :laugh:. Robert
-
Hi, if I understand you correctly one could overcome this problem by starting another thread where the waiting takes place. Thus the request processing thread won't be blocked. Nevertheless I agree that there is one thread more active than necessary. The best solution definitely depends on the context where the code is executed in. To be honest I also tried to just get the shortest solution I could think of. I think regarding this my code should be in the premier league :laugh:. Robert
Robert Rohde wrote:
I think regarding this my code should be in the premier league .
Sure! So far it is the shortest. But the no-wait solution is also possible with probably same amount of code in LINQ/JavaScript. I want to see whether the LINQ Boy[^] or the JavaScript Man [^] to come up with it.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
As currently I am working on asynchronous programming (and my mind is spinning), this quiz is about a simple async programming problem. Given:
//C# delegates
delegate void ActionComplete();
delegate void Action(ActionComplete onComplete);Functions conforming to
Action
execute asynchronously and invoke the function supplied in theonComplete
parameter when complete. For Example, the followingProcessReport
function conforms to the delegateAction
.void ProcessReport(ActionComplete onReportProcessed)
{
//Start a thread to do actual processing and return
//Call onReportProcessed from the thread when processing is done
}Now the real problem: You have a an array of such asynchronous functions and the objective is to execute them one by one in order and call a callback when all the functions have finished executing.
void ExecuteActions(Action[] actions, ActionComplete onAllActionsComplete)
{
}onAllActionsComplete
should be called only once when all the actions have finished executing in order. If there are 3 actions,onAllActionsComplete
should be called whenactions[2]
completes,actions[2]
should start afteractions[1]
completes,actions[1]
should start whenactions[0]
completes.actions[0]
should start first. -------------------------------------- Here is a C++ STL solution to last weeks quiz[^]. It is almost as simple as the python or haskell solution.bool SameSetOfCharacters(string str1, string str2)
{
typedef CharSet std::set<char>;
return CharSet(str1.begin(), str1.end()) == CharSet(str2.begin(), str2.end());
}-- modified at 16:57 Friday 17th November, 2006
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
As you suspected, this sort of thing is trivial in JS. Of course, it helps that JS is single-threaded, but functions as objects and closures make it even easier. Here's a quick-and-dirty (read: untested) solution:
function ExecuteActions(actions, onAllActionsComplete)
{
var loop = function(i)
{
if ( i < actions.length )
actions[i](function() { loop(i+1) });
else
onAllActionsComplete();
}
loop(0);
} -
As you suspected, this sort of thing is trivial in JS. Of course, it helps that JS is single-threaded, but functions as objects and closures make it even easier. Here's a quick-and-dirty (read: untested) solution:
function ExecuteActions(actions, onAllActionsComplete)
{
var loop = function(i)
{
if ( i < actions.length )
actions[i](function() { loop(i+1) });
else
onAllActionsComplete();
}
loop(0);
}Exactly, this is what I ended up implementing in JS (hence the quiz). :) BTW my version looked something like following:
function ExecuteActions(actions, onAllActionsComplete) {
var i = 0;
function nextAction() {
if ( i < actions.length )
actions[i++](nextAction);
else
onAllActionsComplete();
}
nextAction();
}
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
Exactly, this is what I ended up implementing in JS (hence the quiz). :) BTW my version looked something like following:
function ExecuteActions(actions, onAllActionsComplete) {
var i = 0;
function nextAction() {
if ( i < actions.length )
actions[i++](nextAction);
else
onAllActionsComplete();
}
nextAction();
}
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
-
Actually my problem was in JavaScript/Ajax so I could not create threads. But it was fun to solve using anonymous functions and closures. PS I am sorry for hijacking the Friday Programming Quiz started by you.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan
Rama Krishna Vavilala wrote:
I am sorry for hijacking the Friday Programming Quiz started by you.
No need to apologize! You're doing a fantastic job! :) Marc
People are just notoriously impossible. --DavidCrow
There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith