I'm new to multithreading so I was trying to create a basic program that creates an array of size 1000 of random integers and create two threads, one that sorts the array ascendingly and the other sorts the array descendingly (without any concurrency control). So my problem is that the two threads does not read the proper size of the array and when I print out the array length it gives 2, so if I add another argument to the function indicating the size of the array(which is the regular fix) I won't be able to pass that extra argument to the thread created as it only takes 1 argument for the function . Here is what the code looks like :
#include<stdio.h>
#include<pthread.h>
#include<time.h>
void *Function1(int *arr[]){
int i,j,k;
int n = ( sizeof(arr) / sizeof(int));
printf("Size of array = %d\n", sizeof(arr));
printf("Size of int = %d\n", sizeof(int));
printf("no. of elements in array = %d\n", n);
for(i=0;i<n;i++){
for(j=0;j<n-i;j++){
if(arr[j]>arr[j+1]){
int tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
}
}
for(k=0; k<n; k++){
printf("a[%d] is %d Thread#1 \n", k, arr[k]);
}
}
void *Function2(int *arr[]){
int i,j,k;
int n = ( sizeof(arr) / sizeof(int));
printf("Size of array = %d\n", (int)sizeof(arr));
printf("Size of int = %d\n", sizeof(int));
printf("no. of elements in array = %d\n", n);
for (i = 0; i < n; i++){
for (j = i + 1; j < n; j++){
if (arr[i] < arr[j])
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for(k=0; k<n; k++){
printf("a[%d] is %d Thread#2\n", k, arr[k]);
}
}
int main(){
int i,j;
int array[1000];
srand(time(NULL));
for(i=0; i<1000;i++){
array[i] = (rand() % 1000) +1;
}
pthread_t t1,t2;
pthread_create(&t1, NULL, Function1, array);
pthread_create(&t2, NULL, Function2, array);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
Here is what gets printed :
Size of array = 8
Size of array = 8
Size of int = 4
Size of int = 4
no. of elements in array = 2
no. of elements in array = 2
a[0] is 365 Thread#1
a[0] is 365 Thread#2
a[1] is 72 Thread#1
a[1] is 72 Thread#2