Executing functions in parallel?

Max Nowak
Kilo Sage

Hi,

I want to execute multiple functions in parallel (i.e. spawning multiple executions of that function) from a for loop, is that even possible? In the example below, I would have expected (or rather, hoped) that the for loop basically spawns 3 parallel executions of the getData()-function, so that the total execution time would be 10 seconds. Instead, the execution time is 30 seconds.

function getData(element,index,array) { 
    // sleep 10 seconds
    gs.sleep(10000);
    gs.info('Finished execution for ' + element + ' at ' + Date.now());
}

var arr = ['client1','client2','client3'];
arr.forEach(getData);

// Log:
*** Script: Finished execution for client1 at 1660832916531
*** Script: Finished execution for client2 at 1660832926532
*** Script: Finished execution for client3 at 1660832936533

 

I'm guessing this won't be possible, but just to be safe, I wanted to ask the community.

Thanks in advance for any help,

Max

2 REPLIES 2

Mohith Devatte
Tera Sage
Tera Sage

Hello @Max Nowak ,

you can try this script 

function getData(element,index,array) { 
    // sleep 10 seconds
    gs.sleep(10000);
    gs.info('Finished execution for ' + element + ' at ' + Date.now());
}

var arr = ['client1','client2','client3'];
for(var i=0; i<arr.length; i++)
{
getData(arr[i]);
}

Hope this helps 

MARK MY NASWER CORRECT IF IT HELPS YOU

 

palanikumar
Giga Sage

Hi,

You are correct. The executions are sequential. It will wait for the function to execute and then go to next iteration. I don't think there is any option to run in parallel.

Thank you,

Palani

Thank you,
Palani