In: Computer Science
The purpose of this project is to practice the pthread built in functions.
The following c program is a simple program to make a matrix of integers and print it.
//File name: a.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int** a;
int main(){
time_t t;
int m, n, i, j; //m is the numbers of rows and n is the number of columns.
printf("Enter the number of rows, and columns: ");
scanf("%d%d", &m, &n);
printf("%d, %d\n", m, n);
srand((unsigned) time(&t));
a=(int**) malloc(m*sizeof(int*));
for(j = 0; j < n; j++)
a[j] = (int*) malloc(n * sizeof(int*));
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
a[i][j] = rand() % 1000;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++)
printf("%d,", a[i][j]);
printf("\n");
}
return 0;
}
Your project uses pthread built-in functions based on the following conditions:
1. The program reads from the console the number of rows and the number of columns (like the above program). Therefore, the matrix has m rows and n columns.
2. The program creates m threads.
3. Each thread assigns random numbers to one row of the matrix.
4. The function main, sorts each row.
5. Each thread displays its sorted row.
6. The function: main displays the entire matrix.
Answer:
To compile
gcc a.c -pthread
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include<pthread.h>
#include<unistd.h>
int** a;
// a structure for passing argument in thread
typedef struct {
int row;
int col;
}args;
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
void* fun(void * arg){
args* temp = (args *)arg;
qsort(a[temp->row],temp->col,sizeof(int),cmpfunc);
for(int i=0;i<temp->col;i++)printf("%d,",a[temp->row][i]);
printf("\n");
return NULL;
}
int main(){
time_t t;
int m, n, i, j; //m is the numbers of rows and n is the number of columns.
printf("Enter the number of rows, and columns: ");
scanf("%d%d", &m, &n);
printf("%d, %d\n", m, n);
srand((unsigned) time(&t));
a=(int**) malloc(m*sizeof(int*));
for(j = 0; j < n; j++)
a[j] = (int*) malloc(n * sizeof(int*));
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
a[i][j] = rand() % 1000;
pthread_t tid[m];
for(int i=0;i<m;i++){
args arg ;
arg.row = i;
arg.col = n;
pthread_create(&tid[i],NULL,fun,(void *)&arg);
usleep(1000); // applied micro sleep so that thread returns correctly
}
for(int i=0;i<m;i++){
pthread_join(tid[i],NULL);
}
printf("\n");
printf("\n");
printf("By main thread\n");
printf("\n");
for(i = 0; i < m; i++){
for(j = 0; j < n; j++)
printf("%d,", a[i][j]);
printf("\n");
}
return 0;
}