Click here to Skip to main content
13,867,032 members
Click here to Skip to main content
Add your own
alternative version


2 bookmarked
Posted 7 Apr 2015
Licenced CPOL

Calculation of pi with Intel® Threading Building Blocks

, 7 Apr 2015
Rate this:
Please Sign up or sign in to vote.
Intel has developed a valuable tool for developing parallel applications called Intel® Threading Building Blocks (Intel® TBB).

Editorial Note

This article is for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers

Intel® Developer Zone offers tools and how-to information for cross-platform app development, platform and technology information, code samples, and peer expertise to help developers innovate and succeed. Join our communities for Android, Internet of Things, Intel® RealSense™ Technology, and Windows to download tools, access dev kits, share ideas with like-minded developers, and participate in hackathon’s, contests, roadshows, and local events.

Many Android* devices have processors with more than one core and knowing how to develop multithreaded applications has become important in the mobile industry. Intel has developed a valuable tool for developing parallel applications called Intel® Threading Building Blocks (Intel® TBB). The Intel® TBB is a cross-platform library of templates for creating parallel programs. It creates and synchronizes streams of data, hiding the details of the architecture and allowing you to work at a higher level of abstraction. Intel® TBB works on all architectures. For Android, use version 4.3 and above.

Build Intel® TBB

  1. Download TBB. You can download Intel® TBB here: I downloaded the sources of the last stable release (4.3 Update 1).
  2. Add NDK to PATH:

    For Windows*:
    • $ SET PATH=%PATH%;
    For Linux*:
    • $ export PATH=$PATH:

  3. Unzip TBB and go to the directory with source code and in src folder. $ cd /src/
  4. Run TBB for Android: $ /ndk-build –C /src/ arch=intel64 compiler=gcc target=android clean tbb tbbmalloc –j This command builds TBB for Android 64 bit. For building TBB for Android 32 bit, change arch=intel64 on arch=ia32. It will build the application for Android 64 bit architecture.
  5. The library is built. In build directory (/build/) you can find directories with libs:,, and and libgnustl_shared. so we will use in our application.

Calculate π

To calculate π you can choose any formula with a definite integral from Wikipedia: I chose this formula:

For this program I modified the formula:For this program I modified the formula: For this program I modified the formula:

For integral calculating I used the rectangle method. The integrated function is divided into N = 107 equal subintervals of length h = 2·10-7. The approximation to the integral is then calculated by adding up the areas (base multiplied by height) of the N rectangles, giving the formula:

Create Application

To create a new Android application:

Create Main Activity

In the res/layout/activity_main.xml paste the following code:

<RelativeLayout xmlns:android=""
    tools:context="intel.example.pitbbcalc.MainActivity" >

        android:orientation="vertical" >

            android:textAppearance="?android:attr/textAppearanceLarge" />

            android:text="@string/start" />

            android:layout_height="wrap_content" >

                android:textAppearance="?android:attr/textAppearanceLarge" />

                android:textAppearance="?android:attr/textAppearanceLarge" />



In the res/values/strings.xml add this code:

<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">PiTBBCalc</string>
    <string name="action_settings">Settings</string>
    <string name="start">Start</string>
    <string name="title">Calculation of π</string>
    <string name="pi_equally">π = </string>


Now the main activity looks like this:

Next we need to implement the Java* interface for our activity. In the src/intel.example.pitbbcalc/ file, add the following code:

package intel.example.pitbbcalc;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private native double onClickCalc();
	private TextView piEqually;
	private TextView piVal;
	protected void onCreate(Bundle savedInstanceState) {
		Button startButton = (Button) findViewById(;
		piEqually = (TextView) findViewById(;
		piVal = (TextView) findViewById(;
		startButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				double val = onClickCalc();

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(, menu);
		return true;

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == {
			return true;
		return super.onOptionsItemSelected(item);

We can add native support by right-clicking on our project in Project Explorer -> Android Tools -> Add Native Support.

On the next window enter the name of the lib of our project and click Finish.

Now we have to implement native code for integral calculating in one thread. In the jni/PiTBBCalc.cpp file, add the following code:

#include <jni.h>
#include <math.h>

double piIntFunc (const double x)
	return sqrt(1 - pow(x, 2.0));

double calcPi()
	const unsigned int n = pow(10.0, 7);
	double a(-1), b(1);
	double h = (b - a) / n;
	double x (a);

	for (unsigned int i (0); i < n; ++i)
		sum += piIntFunc(x);
		x += h;

	sum *= h;

	return 2 * sum;

extern "C"
JNIEXPORT jdouble JNICALL Java_intel_example_pitbbcalc_MainActivity_onClickCalc(JNIEnv *env,
		jobject obj)
	return calcPi();

Let’s try running our application and π calculation in single threaded mode.

To add parallel implementation with Intel® TBB to our project we should edit jni/ is the Makefile for our project, and we need to add the Intel® TBB libs to it:

LOCAL_PATH := $(call my-dir)
TBB_PATH := <tbb_sources>
TBB_BUILD_PATH := /build/linux_intel64_gcc_android_cc4.9_NDKr10b_version_android-L_release

include $(CLEAR_VARS)

LOCAL_CFLAGS += -DTBB_USE_GCC_BUILTINS -std=c++11 -fexceptions -Wdeprecated-declarations -I$(TBB_PATH)/include -I$(TBB_PATH)$(TBB_BUILD_PATH)


include $(CLEAR_VARS)
LOCAL_MODULE    := libtbb

In the jni/ directory, create an file and add the following lines:

APP_ABI := x86_64 APP_GNUSTL_FORCE_CPP_FEATURES := exceptions rtti APP_STL := gnustl_shared

The purpose of is to describe which native modules (i.e., static/shared libraries) are needed by your application. In the line APP_ABI := x86_64 we specify our target architecture.

Now we can try to run our application. If you see the main screen of the application, then Intel® TBB linked successfully and we can start developing our app.

For adding parallelism to the code, we should include the Intel® TBB header: #include "tbb/tbb.h", remove the cycle and add the following code:

double sum = tbb::parallel_reduce(
		tbb::blocked_range<unsigned int>(0,n),
		double(0), // identity element for summation
		[&](const tbb::blocked_range<unsigned int>& r, double sum)->double {
			for( int i=r.begin(); i!=r.end(); ++i )
				sum += piIntFunc(x);
				x += h;
			return sum; // body returns updated value of accumulator
		[]( double x, double y )->double {
			return x+y; // joins two accumulated values

And now, if you run the application it will work in multithreaded mode.


As you can see, developing parallel applications is very easy. By using the calculation of π as an example we were able to successfully demonstrate how to apply the concepts here from single-threaded code to multithreaded code.

Additional Resources


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Android on Intel
United States United States
Intel is inside more and more Android devices, and we have tools and resources to make your app development faster and easier.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190214.1 | Last Updated 7 Apr 2015
Article Copyright 2015 by Android on Intel
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid