iOS Multithreading using Web Workers

Enterprise apps often require a large amount of processing to be performed. To provide the best user experience while fully leveraging the limited device resources, you must perform compute operations on a background thread.

In this recipe, we will discuss how to use the Ti.WebWorkerWrapper module to perform background compute operations. To simulate a compute job, a fibonacci sequence is calculated for random numbers and processed in parallel. The following screenshot shows the recipe running these Web Worker jobs on an iPhone.

iOS Multithreading using Web Workers

Note

This recipe is an iOS-only recipe as it requires Web Workers, which are not yet available for Titanium Android.

Getting ready

This recipe uses the Ti.WebWorkerWrapper CommonJS module and fibonacci.js Web Worker. These modules and other code assets can be downloaded from the source provided by the book, or individually through the links provided in the See also section at the end of this recipe. To install the Ti.WebWorkerWrapper module and Web Worker into your project, simply copy the Ti.WebWorkerWrapper.js and fibonacci.js files into the Resources folder of your Titanium project as highlighted in the following screenshot:

Getting ready

How to do it...

Once you have added the Ti.WebWorkerWrapper module and fibonacci.js file to your project, you next need to create your application namespace and use require to import the module into your app.js file as the following code snippet demonstrates:

//Create our application namespace
var my = {
  workerMod : require('Ti.WebWorkerWrapper'),
  isAndroid : Ti.Platform.osname === 'android'
};

Creating the recipe UI

This recipe provides a basic UI to launch and track the execution of the Web Workers execution of the fibonacci sequence. The following steps detail how to create the main components illustrated in the earlier screenshot:

  1. First a Ti.UI.Window is created. This window will be used to attach and display all UI elements.
    var win = Ti.UI.createWindow({
      backgroundColor: '#fff', title: 'web Workers', 
      barColor:'#000',layout:'vertical',fullscreen:false
    });
  2. Next a series of Ti.UI.Label controls are added to the Ti.UI.Window. These controls will be used to display the progress and results of the Web Workers.
    var worker1 = Ti.UI.createLabel({
      top:20, height:25, left:5, right:5,color:'#000',
      textAlign:'left',text:'Not yet processed - Press Button', 
      font:{fontSize:14, fontWeight:'bold'}
    });
    win.add(worker1);

    Note

    Three additional Web Worker labels are added using the same template as the worker1 label shown in the preceding code snippet.

  3. Finally a Ti.UI.Button is added to the Ti.UI.Window. This button is used to launch the four Web Worker processes used in this recipe.
    var runButton = Ti.UI.createButton({
      title:'Run Web Worker Test', top:40,
      left:10, right:10, height:50, 
    });
    win.add(runButton);

Testing functions

This recipe uses a tests object to assist with timing and displaying the results of the Web Worker fibonacci sequence processing. The following section discusses functionality contained within the tests JavaScript object.

var tests = {
  1. The updateLabel method is used to apply a formatting template to each label with the results of the fibonacci sequence callback results.
      updateLabel : function(label,e){
        label.text = "Seed:" + e.seed + " result:" + 
        e.result + " elapsed:" + e.elapsed + "ms";
      },
  2. The worker1 through worker4 methods are the callback methods provided to each Web Worker as it processes the fibonacci sequence. These callbacks receive the results from the calculation process.
      worker1 : function(e){
        tests.updateLabel(worker1,e);
      },
      worker2 : function(e){
        tests.updateLabel(worker2,e);
      },
      worker3 : function(e){
        tests.updateLabel(worker3,e);
      },
      worker4 : function(e){
        tests.updateLabel(worker4,e);
      },
  3. The random method is used to generate a random number within a given range. This method is used to generate the random number sent to the fibonacci sequence.
      random : function(from,to){
        return Math.floor(Math.random()*(to-from+1)+from);
      }
    };

Multithreading using Web Workers

The multithreading example is run when the user taps on the runButton button. The following section demonstrates how four Web Workers are created in the background. Once each Web Worker has finished processing, the results are provided to the test's callback method discussed earlier in this recipe.

runButton.addEventListener('click',function(e){
  1. First a new worker object is created by initializing a new instance of the Ti.WebWorkerWrapper module.
      var worker1 = new my.workerMod();
  2. Next, the start method is called on the worker object. The start method requires the following arguments:
    • The path of the JavaScript file the Web Worker should execute
    • A random number passed as a Web Worker postMessage for the fibonacci sequence to use
    • The callback method to be used when the Web Worker has completed processing
        worker1.start('fibonacci.js',tests.random(1,50),
        tests.worker1);
  3. Three additional Web Workers are created using the same pattern demonstrated in the creation of worker1.
      var worker2 = new my.workerMod();
      worker2.start('fibonacci.js',tests.random(1,50),
      tests.worker2);
    
      var worker3 = new my.workerMod();
      worker3.start('fibonacci.js',tests.random(1,50),
      tests.worker3);
    
      var worker4 = new my.workerMod();
      worker4.start('fibonacci.js',tests.random(1,50),
      tests.worker4);
    
    });

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.149.180