类声明
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
class event_t {
public:
event_t(String *_session_time, String *_event_type, String *_table_name, String *_num_of_events);
~event_t();
char *table_name;
char *event_type;
pthread_mutex_t lock;
pthread_cond_t cond;
int num_of_events_threshold;
double time_out;
int num_of_events_so_far;
};
std::map <char*, std::list<event_t*>, cmp_str > all_events; //global map
我有这个函数等待变量达到某个阈值,这个阈值是通过pthread_cond和pthread_mutex完成的。然后它返回。最后一行给出了分段错误。
void foo(){
//don't worry event object ic created properly
event_t *new_event = new event_t(args[0]->val_str(s),(args[1]->val_str(s)), (args[2]->val_str(s)), (args[3]->val_str(s)));
map<char*, list<event_t*> >::iterator map_it;
map_it = all_events.find(new_event->table_name);
if(map_it == all_events.end()){
list<event_t*> *my_list = new list<event_t*>();
my_list->push_back(new_event);
all_events[new_event->table_name] = *my_list;
}
else{
map_it->second.push_back(new_event);
for (list<event_t*>::iterator list_it=map_it->second.begin(); list_it!=map_it->second.end(); ++list_it)
std::cout << (*list_it)->event_type << " " << (*list_it)->time_out << " " << (*list_it)->num_of_events_threshold << '\n';
}
/*
* waiting for number of events reach its threshold.
*/
pthread_mutex_lock(&new_event->lock);
while(new_event->num_of_events_so_far < new_event->num_of_events_threshold )
pthread_cond_wait(&new_event->cond, &new_event->lock);
pthread_mutex_unlock(&new_event->lock);
// segmentation fault!!!
for (list<event_t*>::iterator list_it=map_it->second.begin(); list_it!=map_it->second.end(); ++list_it)
std::cout << (*list_it)->event_type << " " << (*list_it)->time_out << " " << (*list_it)->num_of_events_threshold << '\n';
}
答案 0 :(得分:1)
if(map_it == all_events.end()){
list<event_t*> *my_list = new list<event_t*>();
my_list->push_back(new_event);
all_events[new_event->table_name] = *my_list;
}
此代码不会将map_it
指向有效的迭代器,因此当您在函数底部取消引用它时,它将崩溃。
您可能想添加一行
map_it = all_events.find(new_event->table_name);
在if { }
子句中。