Threads

134 views 10:26 am 0 Comments March 28, 2023

 

5004CEM Lab 18

Threads

In this lab, you will create a program that makes use of threads to process numbers.

You could create the program using a programming language of your choice or adapt the code (pthread_count.cc) provided in Session18 on the server or on AULA.

See the ‘Getting Started with Lab 18’ video on AULA to give you additional information on completing this lab.

If you have any additional questions on this lab or any other labs please do not hesitate to ask your tutor and/or email me on [email protected].

Task – Threads

Create a program that has an array of numbers of length N. The program should create M threads, each of which will process N/M items in the array. In this case, the “processing” is simply a matter of squaring the numbers. When all threads are complete, the program should display the complete contents of the array.

Solution

Square.cc

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <unistd.h>

void *process_thread( void *ptr );

//N

int numItems=100;

//M

int numThreads=50;

//A counter just to uniquely ID the threads for output

int threadCount=0;

pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;

int main(int argc,char* argv[]){

pthread_t threads[numThreads]; //Store thread IDs

int vals[numItems];

for(int i=0;i<numItems;i++){ //Fill with numbers

vals[i]=i;

}

for(int i=0;i<numThreads;i++){

pthread_create(

&threads[i],

NULL, process_thread,(void*) &vals[i*(numItems/numThreads)]

);

}

for(int i=0;i<numThreads;i++){

pthread_join( threads[i], NULL);

}

return 0;

}

void *process_thread( void *ptr ){

pthread_mutex_lock(&mx);

int myID=threadCount++;

printf(“Thread number %d initialisedn”,myID);

//sleep(1);

for(int i=0;i<(numItems/numThreads);i++){

printf(“(Thread %d) Processing item: was %d “,myID,((int*)ptr)[i]);

//Alternative way to address elements

//printf(“(Thread %d) Processing item: was %d “,myID,*((int*)(ptr+i*sizeof(int))));

//Square the values

((int*)ptr)[i] *= ((int*)ptr)[i];

//No need to worry about other threads printing in between due to the mutex

printf(“now %d n”,((int*)ptr)[i]);

}

//printf(“Val:%dtID:%dn”,val,*((int*)(ptr)));

pthread_mutex_unlock(&mx);

}

Lab Evidence

Source code, with sensible comments showing how the task is complete.

Output of the program showing the threads completing the problem.