我是多线程的新手,所以我试图创建一个基本程序,创建一个大小为1000的随机整数数组并创建两个线程,一个对数组进行升序排序,另一个对数组进行降序排序(没有任何并发性)控制)。所以我的问题是两个线程没有读取数组的正确大小,当我打印出数组长度时它给出2,所以如果我在函数中添加另一个参数来指示数组的大小(这是常规修复) )我将无法将该额外参数传递给创建的线程,因为它只需要1个函数参数。这是代码的样子:
#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;
}
以下是打印的内容:
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