指针的成员变量由于某种原因而改变了?

时间:2019-04-04 01:40:10

标签: c++ pthreads member-variables

我正在为调度程序运行一个线程,并在调度程序线程仍在运行时将进程插入到主线程中的调度程序队列中。无论出于何种原因,当将对象本身传递到ReadyQueue时,过程对象的变量都会更改。例如,我传入了100 msBurstTime,当我在线程中打印它时说它是32571。 这是线程执行的调度程序代码:

void Scheduler::startThread(CPU *cpu, IO_manager *io_m){
    this->link(cpu, io_m);
    pthread_t thread;
    pthread_create(&thread, NULL, Scheduler::staticThreadEntry, this);
}

void Scheduler::FCFS(){
    while (true){
        sleep(2);
        if (this->ReadyQueue.size() > 0 && cpu->getRunningProcess() == NULL){
            std::cout << this->ReadyQueue.at(0) << ' ';
            // burst time out of whack here (32571 ms)
            std::cout << this->ReadyQueue.at(0)->getBurstTime() << std::endl;
            //std::cout << "Dispatched process" << std::endl;
            //this->dispatchProcess();
        }
        //std::cout << "CPU occupied" << std::endl;
    }
}

void* Scheduler::staticThreadEntry(void *self){
    ((Scheduler*) self)->FCFS();
}

这是将进程插入调度程序的ReadyQueue的地方:

void Scheduler::insertProcess(Process *p){
    // burst time fine here (100 ms)
    this->ReadyQueue.push_back(p);
}

这是在main.cpp中调用的以初始化调度程序的内容:

scheduler.startThread(&cpu, &io_m);

这是在main.cpp中所谓的将进程插入调度程序的ReadyQueue中的内容:

if (strcmp(args[0], "newp") == 0){
    // args[1] is process status, args[2] is ms burst time
    Process p(stoi(args[1]), stoi(args[2]));
    scheduler.insertProcess(&p);
}

为什么会这样?我检查了过程对象的引用,它是同一实例,那么为什么成员变量会发生变化?

1 个答案:

答案 0 :(得分:0)

<v-select
    v-model="selectedPickupLocation"
    :options="storeLocationsArray"
    label="address"
>
</v-select>

您已要求if (strcmp(args[0], "newp") == 0){ // args[1] is process status, args[2] is ms burst time Process p(stoi(args[1]), stoi(args[2])); scheduler.insertProcess(&p); } 存储指向即将停止存在的对象scheduler的指针。指向不再存在的对象的指针无济于事。

使用原始指针的集合几乎从来都不明智。它使得不清楚对象拥有什么以及如何管理对象的生存期。尽可能使用值。否则,请考虑使用p,或在必要时考虑使用std::unique_ptr

相关问题