是否mutex
在pthread
库中与 fromc++
相同的synchronized
关键字Java
(无论我放在里面的调用函数是线程安全的)吗?我有城市列表
pthread_t thread1;
class City{
public:
std::string name;
int citizens;
std::string state;
std::string it_company;
};
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
std::list<City> cities;
void* manage_cities(void*){
pthread_mutex_lock(&lock);
work_on_every_instance_of_list();//works on list cities
pthread_mutex_unlock(&lock);
}
/*
* This function is called periodically
*/
void update_cities(){
pthread_create( &thread1, NULL, &manage_cities, NULL);
pthread_mutex_lock(&lock);
for(std::list<City>::iterator iter=cities.begin();iter!=cities.end();++iter){
std::cout<<(*iter).name<<"\n";
}
pthread_mutex_unlock(&lock);
}
它在迭代中抛出异常,如Access location
. 这是正确的做法还是我误解了互斥锁?