【发布时间】:2014-08-15 15:33:50
【问题描述】:
我已经用 C 编写了我的第一个多线程程序。特别是:程序接收一个 int 参数,该参数指定 main 中 int 类型数组的大小。该数组将随机分配和填充。我想研究多线程程序和单线程程序之间的时间差异。因此,我编写了上述程序的两个“相同”版本。 “标准”程序运行良好,一切正常,例如:
$ ./prog 10000
all done
real 0m0.244s
user 0m0.238s
sys 0m0.004s
这是非线程程序的输出。
但是,当我运行线程程序时,我得到了这个错误:
Segmentation fault: 11
我已经看到这个错误代码是关于指针的错误(通常在分配的内存区域之外),但是这次我找不到我提交的错误/错误。会是累,会是我是初学者,但现在我看不到我的错误。有人可以帮我吗?
线程程序的源代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *order(int * v, int x, int y);
void printv(int * v, int dim);
int main (int argc, const char *argv[]) {
int *v = NULL;
int x = 0;
int dim = 0;
pthread_t bot1 = NULL, bot2 = NULL, bot3 = NULL, bot4 = NULL;
void *retval;
if (argc != 2) {
fprintf(stderr, "usage: %s [arraySize]\n", argv[0]);
exit(EXIT_FAILURE);
}
dim = atoi(argv[1]);
if (dim <= 0) {
fprintf(stderr, "usage: %s [arraySize] in which [arraySize] must be an integer > 0\n", argv[0]);
exit(EXIT_FAILURE);
}
v = (int *) malloc (dim * sizeof (int));
if (v == NULL) {
fprintf(stderr, "array allocation error\n");
exit(EXIT_FAILURE);
}
// Initial array
fprintf(stdout, "the initial array is: ");
printv(v, dim);
fprintf(stdout, "\n\n");
// Randomize array
for (x = 0; x < dim; x++) {
v[x] = rand()%100;
}
fprintf(stdout, "the randomized array is: ");
printv(v, dim);
fprintf(stdout, "\n\n");
// Ordering array
// WARNING: "OVERLAP SECTOR BEGIN"
pthread_create(&bot1, NULL, order(v, 0, dim/4), NULL);
pthread_create(&bot2, NULL, order(v, dim/4, dim/2), NULL);
pthread_create(&bot3, NULL, order(v, dim/2, (dim/4)*3), NULL);
pthread_create(&bot4, NULL, order(v, (dim/4)*3, dim), NULL);
pthread_join(bot1, &retval);
pthread_join(bot2, &retval);
pthread_join(bot3, &retval);
pthread_join(bot4, &retval);
// WARNING: "OVERLAP SECTOR END"
fprintf(stdout, "the ordered array is: ");
printv(v, dim);
fprintf(stdout, "\n\n");
// End main
fprintf(stdout, "all done\n");
return 0;
}
void *order (int * v, int x, int y){
int i = 0;
int j = 0;
int tmp = 0;
for (i = x; i < y; i++) {
for (j = x; j < y; j++) {
if (v[i] < v[j]) {
tmp=v[i];
v[i]=v[j];
v[j]=tmp;
}
}
}
return 0;
}
void printv (int * v, int dim) {
int x = 0;
for (x = 0; x < dim; x++) {
fprintf(stdout, "%d ", v[x]);
}
fprintf(stdout, "\n\n\n");
return;
}
问候。
附: 错误发生在“重叠扇区”(在 cmets 中描述)之前和数组填充操作之后。
【问题讨论】:
标签: c arrays multithreading pthreads