[英]Priority Queue C++
我在C ++中创建了以下优先级队列
priority_queue < ThreadInfo*, vector<ThreadInfo*>, CompareThread > thread_queue;
ThreadInfo类的位置
class ThreadInfo {
public:
ThreadInfo();
ThreadInfo(const ThreadInfo& orig);
ThreadInfo(int thread_id,int init_time,int sleep_time,int run_time,int priority,int is_critical)
{
this->thread_id=thread_id;
this->is_critical=is_critical;
this->init_time=init_time;
this->priority=priority;
this->run_time=run_time;
this->sleep_time=sleep_time;
}
void set_critical(bool value)
{
is_critical=value;
}
bool get_critical()
{
return is_critical;
}
void set_sleep_time(long value)
{
sleep_time=value;
}
long get_sleep_time(long value)
{
return sleep_time;
}
void set_run_time(long value)
{
sleep_time=value;
}
long get_run_time(long value)
{
return sleep_time;
}
int get_lock_type()
{
return lock_type;
}
void set_lock_type(int lock_type)
{
this->lock_type=lock_type;
}
int get_priority()
{
return priority;
}
void set_priority(int value)
{
this->priority=value;
}
unsigned long int get_thread_id()
{
return thread_id;
}
void set_thread_id(unsigned long int value)
{
this->thread_id=value;
}
virtual ~ThreadInfo();
private:
unsigned long int thread_id;
long init_time;
long sleep_time;
long run_time;
int priority;
bool is_critical;
//1=spin,2=busy,3=semaphore
int lock_type;
};
而比较类是
class CompareThread {
public:
bool operator()(ThreadInfo* th1, ThreadInfo* th2)
{
if (th1->get_priority()>th2->get_priority()) return true;
return false;
}
};
然后我在以下函数中插入元素,
void ThreadScheduler::register_thread(ThreadInfo &th)
{
thread_queue.push(&th);
}
我从以下函数调用线程寄存器,
int ThreadController::thread_register(pthread_t &t, int priority, bool critical)
{
ThreadInfo ti;
cout<<"t reg:"<<t<<endl;
ti.set_thread_id(t);
ti.set_critical(critical);
ti.set_priority(priority);
ThreadScheduler::Instance()->register_thread(ti);
}
但每当我将一些threadinfo对象推送到队列时,我在调用thread_queue.top()时会得到最新的对象,是否应返回优先级最低的线程对象。 这里有什么问题吗?
您正在将指向同一内存块的指针传递到队列中。 您正在使用对本地对象的引用调用register_thread并将其地址排队。 这就是他们都一样的原因。 另一个问题是,当你离开thread_register
函数时,本地ti
将被删除(超出范围),你将在队列中没有有效的条目。
您需要做的是为每个信息分配新内存并将数据复制到此内存中。 因此,您插入队列的每个元素指针必须来自不同的new
元素,如果您有一个复制构造函数,它将执行以下操作:
void ThreadScheduler::register_thread(ThreadInfo &th)
{
thread_queue.push(new ThreadInfo(th));
/* ... */
}
问题是您正在使用指向函数本地声明的变量的指针。 一旦函数( ThreadController::thread_register
)完成,局部变量就不再存在,指针现在指向一些未分配的内存。
有两种解决方案:
使用智能指针,如std::shared_ptr
,并在ThreadController::thread_register
创建一个新指针:
std::shared_ptr<ThreadInfo> ti(new ThreadInfo);
当然,您必须记住在其他地方更改为std::shared_ptr
,并使用->
access运算符而不是.
。
根本不使用指针,让类数据(非常简单和简单)被复制。
我建议选择2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.