Created
          April 25, 2019 10:56 
        
      - 
      
 - 
        
Save yowcow/f07e26e7a64b65b3a954403931a59a0d to your computer and use it in GitHub Desktop.  
    First come first served job scheduler with max concurrency
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | -module(scheduler). | |
| -export([ | |
| run/0 | |
| ]). | |
| -define(MAX_CONCURRENCY, 3). | |
| run() -> | |
| Msgs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
| run(Msgs, ?MAX_CONCURRENCY, 0, 0, 0). | |
| run([], _, 0, Sent, Received) -> [{sent, Sent}, {received, Received}]; | |
| run([], Max, Cur, Sent, Received) -> | |
| ok = wait(), | |
| run([], Max, Cur-1, Sent, Received+1); | |
| run([Msg | Msgs], Max, Cur, Sent, Received) when Cur =:= Max -> | |
| ok = wait(), | |
| work(Msg), | |
| run(Msgs, Max, Cur, Sent+1, Received+1); | |
| run([Msg | Msgs], Max, Cur, Sent, Received) when Cur < Max -> | |
| work(Msg), | |
| run(Msgs, Max, Cur+1, Sent+1, Received). | |
| work(Msg) -> | |
| Self = self(), | |
| Pid = spawn(fun() -> do_work(Self, Msg) end), | |
| io:format("sent work ~p to ~p ~n", [Msg, Pid]). | |
| wait() -> | |
| receive | |
| {From, Msg} -> | |
| io:format("got result ~p from ~p ~n", [Msg, From]), | |
| ok | |
| end. | |
| do_work(From, Msg) -> | |
| Self = self(), | |
| Rand = rand:uniform(10), % let's say each message requires max 10 seconds to complete | |
| timer:sleep(Rand * 1000), | |
| From ! {Self, Msg}. | 
      
      
  Author
  
  
      
          
      
      
            yowcow
  
      
      
      commented 
        Apr 25, 2019 
      
    
  
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment