I am trying to sort an array with length of 1000 using 10 threads. The first thread is 0 to 99 and the second is 100 to 199.... My problem is that only the first 100 elements are sorted and the rest are left untouched even though the threads run as expected in all aspects other than sorting.
#define N 1000
int arr[N];
int main(int argc, char *argv[])
{
int i;
//Filling the array with random integers
for(i=0;i<N;i++)
{
arr[i]=1+rand()%200;
}
for(i=0;i<N;i++)
{
printf("%d | ",arr[i]);
}
printf("\n");
/* START OF THREAD SECTION */
pthread_t sorters[10];
for(i=0;i<10;i++)
{
pthread_create(&sorters[i],NULL,sortArr,(void*)i);
pthread_join(sorters[i],NULL);
}
/* END OF THREAD SECTION */
return 0;
}
thread:
void* sortArr(void *num)
{
int i,j,temp,cast,first=0,last;
//Casting
cast=(intptr_t)num;
//Calculating first and last element
first=(cast*100);
last=first+99;
printf("first %d , last %d \n",first,last);
printf("Not sorted:\n");
for(i=first;i<last;i++)
{
printf("%d | ",arr[i]);
}
printf("\n");
/* SORTING */
for (i = first; i < last-1; i++)
{
for (j = first; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
/* SORTING */
printf("Sorted:\n");
for(i=first;i<last;i++)
{
printf("%d | ",arr[i]);
}
printf("\n");
}
With my current knowledge I can only try so many things to figure it out and any help would be much appreciated.
答案 0 :(得分:2)
如果first
不为0,内循环退出条件会立即退出。应该是
for (j = first; j < last + first - i; j++)
这10个线程也毫无意义,因为它们并不是并行运行的。您应该将join移动到单独的循环中。