我得到了这个分段错误。
它将运行第一个方法,然后运行第二个方法的printf行,然后直接进入分段错误。 我不明白为什么......我解除了以前的分配。 我的第二个方法运行的那一刻,它将输出prinf语句:client然后分段错误
void
ThreadTest()
{
DEBUG('t', "Entering SimpleTest");
printf("THREAD TEST\n");
Thread *s = new Thread("thread");
s->Fork(client2,1);
Thread *g = new Thread("thread");
g->Fork(client, 1);
}
我的第一个方法
void
client2(int which)
{
DEBUG('t', "Entering SimpleTest");
printf("client2\n");
int urlSize;
const int sz = 50;
char url[sz];
FILE *fp = fopen("url.txt", "r");
if (!fp)
printf(" Cannot open file url.txt!\n");
else {
int pos = 0;
char c = getc(fp);
while (c != EOF || pos == sz - 1)
{
if (c == '\n')
{
url[pos] = '\0';
//serve(url);
pos = 0;
//url size
urlSize = sizeof(url)/sizeof(url[0]);
//---------------------------------------------------------------------------
urlList = (List*)malloc(urlSize*sizeof(List));
//---------------------------------------------------------------------------
clientTXT.P(); //wait
mutex2.P();//entering critical region
urlList -> Append(url);
cout<<"urls: "<< url<<endl;
mutex2.V();//leaving critical region
clientURL.V();// increment slots or client url request objects
//--------------------------------------------------------------------------
free(urlList);
//---------------------------------------------------------------------------
}
else
{
url[pos++] = c;
}
c = getc(fp);
}
fclose(fp);
printf("No more URLs\n");
}
}
运行第二种方法
void
client(int request)
{
DEBUG('t', "Entering SimpleTest");
printf("client\n");
int urlSize;
while(TRUE){
char* nextUrl;
printf("segment");
nextUrl = (char*)urlList->Remove();
urlSize = sizeof(nextUrl)/sizeof(nextUrl[0]);
Request *reqq = new Request(nextUrl, urlSize, request, 1);
//---------------------------------------------------------------------------
reqList = (List*)malloc(urlSize*sizeof(List));
//--------------------------------------------------------
clientURL.P(); //wait
mutex.P(); //entering critical region
reqList->Append(reqq);
cout<<"urldest: "<<(reqq->urlDest)<<endl;
mutex.V(); //exit critical region
serverURL.V(); //signal
//--------------------------------------------------------
free(reqList);
//---------------------------------------------------------------------------
}
}
答案 0 :(得分:1)
问题很可能发生,因为您没有同步urlList
的访问权限。
在client2
中,您正在分配urlList
,然后在client
中访问它,但无法保证两个线程的执行顺序。考虑使用同步原语来控制对urlList
的访问,以确保在访问它之前分配它。