6CS005 Week 4 Workshop
6CS005 Week 4 Workshop
You may need to refer to the Week 4 lecture slides in order to complete these tasks.
1. The following program prints out "Hello World!" with the default number of threads which is
usually the number of CPU processor cores that are on your computer system:
#include <stdio.h>
void main()
{
#pragma omp parallel
printf("Hello world from OpenMP!\n");
}
a. Enter and run the program to see how many processor cores are on the system you are using.
b. Modify the program so that it run with exactly 10 threads.
2. The following program prints out all the prime numbers from 1 to 1000:
#include <stdio.h>
void main()
{
int i, c;
printf("Prime numbers between 1 and 1000 are :\n");
for(i = 1; i <= 1000; i++){
for(c = 2; c <= i - 1; c++){
if ( i % c == 0 )
break;
}
if ( c == i )
printf("%d\n", i);
}
}
Convert this to a multithread OpenMP program using the default number of threads to calculate the
prime numbers.
3. Convert the above program so that it uses exactly 5 threads and each thread prints out their thread ID
when they print out their prime number.
4. Modify the program in (3) so that the program prints out the total number of prime numbers found.
Check this whether this is correct by running it with exactly 1 thread.
5. The following PThreads program demonstrates 3 thread sending string messages to each other, using
a global array. The messages are meant to be sent in the following order:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
/* Receiving a message */
printf("Thread %ld received the message '%s'\n",tid, messages[tid]);
free(messages[tid]);
messages[tid] = NULL;
}
return NULL;
}
void main()
{
pthread_t thrID1, thrID2, thrID3;