C Pthread连接分段错误
我有下面的代码,其中两个数组通过两个线程进行了不同的修改(在一种情况下,每个元素递增1,在另一种情况下,每个元素递减1)。它给出了分段错误。你能指出错误吗C Pthread连接分段错误,c,multithreading,pthreads,C,Multithreading,Pthreads,我有下面的代码,其中两个数组通过两个线程进行了不同的修改(在一种情况下,每个元素递增1,在另一种情况下,每个元素递减1)。它给出了分段错误。你能指出错误吗 #include <stdio.h> #include <pthread.h> #include <stdlib.h> void *decrement(void *object){ int *array = (int *)object; for(int i=0;i<5;i++){ a
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *decrement(void *object){
int *array = (int *)object;
for(int i=0;i<5;i++){
array[i]=array[i]-1;
}
}
void *increment(void *object){
int *array = (int *)object;
for(int i=0;i<5;i++){
array[i]=array[i]+1;
}
}
int main(int argc, char const *argv[]){
int segments = 2;
pthread_t threads[segments];
int i;
int numbers[5] = {1,3,2,9,11};
int numbers1[5] = {0,14,12,4,10};
int *array;
array=numbers;
pthread_create(&threads[0], NULL, increment, (void *) &array);
int *array1;
array1=numbers1;
pthread_create(&threads[1], NULL, decrement, (void *) &array1);
for(i = 0; i < 2; i++){
pthread_join(threads[i], NULL);
}
for(i = 0; i < 5; i++){
printf("%d\n", array[i]);
printf("%d\n", array1[i]);
}
pthread_exit(NULL);
}
#包括
#包括
#包括
无效*减量(无效*对象){
int*数组=(int*)对象;
对于(int i=0;i让我们取以下几行:
int *array;
array=numbers;
pthread_create(&threads[0], NULL, increment, (void *) &array);
在这里,您将变量array
的地址传递给线程函数,但是当array
本身指向数组时,变量的地址并不指向数组
如果要使用临时变量,只需单独使用变量即可:
pthread_create(&threads[0], NULL, increment, array);
请注意缺少cast和操作员地址
但是您实际上并不需要临时array
变量,因为数组会衰减为指针,所以您可以这样做
pthread_create(&threads[0], NULL, increment, numbers);
为了更形象地说明您的问题,您所拥有的是:
+--------+ +-------+ +---------+
| &array | ---> | array | ---> | numbers |
+--------+ +-------+ +---------+
+--------+ +-------+ +---------+
|&array |-->| array |-->|编号|
+--------+ +-------+ +---------+
问一下,size
在线程函数中有什么用途?