我有这个程序:
#include <stdio.h>
#niclude ......
struct sort {
char * array;
int left,right;
};
void quicksortthread(struct sort *s){
int left, right;
int i, j, x, tmp;
pthread_t *th1, *th2;
char * v;
struct sort s1;
struct sort s2;
left = s->left;
right = s->right;
v = s->array;
printf("\n\n\n\n QT: l=%i, r=%i \n",left,right);
//sorting algorithm
if (left >= right)
return;
x = v[left];
i = left - 1;
j = right + 1;
while (i < j) {
while (v[--j] > x);
while (v[++i] < x);
if (i < j) {
char temp = v[i];
v[i] = v[j];
v[j] = temp;
}
}
s1.array = v;
s1.left = left;
s1.right = j;
s2.array = v;
s2.left = j+1;
s2.right = right;
printf("1)left = %i; right= %i\n", left,j);
printf("2)left = %i; right= %i\n", j+1,right);
pthread_create(&th1, NULL, quicksortthread,&s1);
pthread_create(&th2, NULL, quicksortthread,&s2);
}
int main (int argc, char ** argv){
pthread_t *th1;
int fd, len, pg, i, j;
int left, right;
struct stat stat_buf;
char c, *paddr;
struct sort s;
/*..LOTS OF THIGS
Define right and left as integers and
paddr as a char *
..*/
if( (right) >= (atoi(argv[2])) ){
//printf("filling structure\n");
s.array = paddr;
s.left = left;
s.right = right;
//printf("creating threads\n");
pthread_create(&th1, NULL, quicksortthread,&s);
}
sleep(100);
}
两次线程调用后,它停止工作。这是因为在函数pthread_create
中传递的结构作为最后一个参数,似乎是不正确的。它编译并执行而没有(例如)分段错误。我确信我正在以正确的方式使用结构和指针。
然后程序以这种方式返回:
left = 0; right= 2048
QT: l=0, r=2048
1)left = 0; right= 0
2)left = 1; right= 2048
left = 0; right= 0
QT: l=0, r=0
left = 1037061890; right= 32542
QT: l=1037061890, r=32542
已解决:我已解决此问题以这种方式更改线程例程:
nt left, right;
int i, j, x, tmp;
pthread_t th1, th2;
char * v;
struct sort * s1;
s1= malloc(sizeof(struct sort *));
struct sort * s2;
s2= malloc(sizeof(struct sort *));
left = s->left;
right = s->right;
printf("\n\n\n\nleft = %i; right= %i\n", left,right);
v = s->array;
printf("QT: l=%i, r=%i \n",left,right);
if (left >= right)
return;
x = v[left];
i = left - 1;
j = right + 1;
while (i < j) {
while (v[--j] > x);
while (v[++i] < x);
if (i < j) {
char temp = v[i];
v[i] = v[j];
v[j] = temp;
}
}
s1->array = v;
s1->left = left;
s1->right = j;
s2->array = v;
s2->left = j+1;
s2->right = right;
printf("1)left = %i; right= %i\n", left,j);
printf("2)left = %i; right= %i\n", j+1,right);
pthread_create(&th1, NULL, quicksortthread,s1);
pthread_create(&th2, NULL, quicksortthread,s2);
答案 0 :(得分:0)
struct sort s
是一个自动变量,你将它的指针传递给线程。这不是一个好习惯。即使在调用pthread_create
的函数返回后,该线程也会存在,在这种情况下,堆栈变量将超出范围。从quicksortthread
函数本身创建线程的方式存在同样的问题,其中struct sort s1
和struct sort s2
是quicksortthread函数的局部变量。最好动态地为这些结构分配内存。
此外,还不清楚为什么在主要内容中添加了sleep(100)
。在退出main之前,您应该使用pthread_join
等待创建的线程完成。
pthread_create
只需要pthread_t *
作为第一个参数,但是,您传递的是pthread**
。 pthread_t *th1
应为pthread_t th1
。