我编写了以下代码,其中父代创建了一个共享内存对象,然后调用fork系统调用API来创建子进程。 正如预期的那样,我面临着不一致的问题,因为它们都会使用共享内存对象,并且会出现竞争条件。 我不明白的是,当我在单处理器上运行任务集的过程时,没有竞争条件? 这种行为背后的原因可能是什么?
//init Attachmem as shared memory object having countval as a member
int main(){
pid_t retval;
int status;
retval=fork();
if(retval<0){
perror("Fork failed\n");
exit(1);
}
printf("When Parent donot waits for child \n\n\n");
if(retval>0){
while(dummycount){
Attachmem->countval++;
dummycount--;
}
printf("PARENT::In parent context value of Countval becomes %d\n",Attachmem->countval); //shared object
printf("PARENT::In parent context value of dummycount becomes %d \n",dummycount); //parent specific object
}
if(retval==0){
dummycount=0;
while(Attachmem->countval){
dummycount++;
}
printf("CHILD::In child context the value of Countval becomes %d\n",Attachmem->countval);
printf("CHILD::In child context the value of dummycount becomes %d\n",dummycount);
error(0);
}
return 0;
}
输出:: 当孩子和家长在不同的处理器上运行时
CHILD::In child context the value of Countval becomes 0
CHILD::In child context the value of dummycount becomes 16897
./a.out: : Unknown error 16897
PARENT::In parent context value of Countval becomes 479145
PARENT::In parent context value of dummycount becomes 0
当子级和父级使用任务集在同一处理器上运行时
PARENT::In parent context value of Countval becomes 500000
PARENT::In parent context value of dummycount becomes 0
When Parent donot waits for child
CHILD::In child context the value of Countval becomes 0
CHILD::In child context the value of dummycount becomes 500000
./a.out: : Unknown error 500000
我目前正在使用linux内核3.16.6运行OpenSuse