Home | | Multi - Core Architectures and Programming | An Example of Requiring Synchronization Between Threads

# An Example of Requiring Synchronization Between Threads

We’ll start an example where two multiple threads are used to calculate all the prime numbers in a given range. Listing 6.11 shows one test to indicate whether a number is prime.

An Example of Requiring Synchronization Between Threads

We’ll start an example where two multiple threads are used to calculate all the prime numbers in a given range. Listing 6.11 shows one test to indicate whether a number is prime.

Listing 6.11   Test for Whether a Number Is Prime

#include <math.h>

int isprime( int number )

{

int i;

for ( i=2; i < (int)(sqrt((float)number)+1.0); i++ )

{

if ( number % i == 0 ) { return 0; }

}

return 1;

}

We will create two threads, both of which will keep testing numbers until all the numbers have been computed. Listing 6.12 shows the code to create the two threads.

Listing 6.12   Code to Create Two Threads and Wait for Them to Complete Their Work

int _tmain( int argc, _TCHAR* argv[] )

{

HANDLE h1, h2;

h1 = (HANDLE)_beginthreadex( 0, 0, &test, (void*)0, 0, 0 );

h2 = (HANDLE)_beginthreadex( 0, 0, &test, (void*)1, 0, 0 );

WaitForSingleObject( h1, INFINITE );

WaitForSingleObject( h2, INFINITE );

CloseHandle( h1 );

CloseHandle( h2 );

getchar();

return 0;

}

The tricky part of the code is where we want each thread to test a different number. Listing 6.13 shows a serial version of the code to do this.

Listing 6.13   Algorithmic Version of Code to Test Range of Numbers for Primality

volatile int counter = 0;

unsigned int __stdcall test( void * )

{

while ( counter<100 )

{

int number = counter++;

printf( "ThreadID %i; value = %i, is prime = %i\n", GetCurrentThreadId(), number, isprime(number) );

}

return 0;

}

However, using two threads to perform this algorithm would cause a data race if both threads accessed the variable counter at the same time. If we did choose to select this particular algorithm, we would need to protect the increment of the variable counter to avoid data races. The following sections will demonstrate various approaches to solv-ing this problem.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Multicore Application Programming For Windows, Linux, and Oracle Solaris : Windows Threading : An Example of Requiring Synchronization Between Threads |