【发布时间】:2012-01-12 04:23:40
【问题描述】:
我正在实现一个简单的线程应用程序,其中有一个服务器线程和一个 gui 线程。所以,事情有点像这样:
int main(int argc, char *argv[]) {
appMain app(argc, argv);
return app.exec();
}
appMain::appMain(int c, char **v) : argc(c), argv(v) {
this->Configuration();
}
int appMain::exec() {
appServer Server;
try {
ServerThread = boost::thread(Server);
ServerThread.join();
} catch (...) {
return EXIT_FAILURE;
}
return 0;
}
appMain::Configuration 方法只是获取一个配置文件并将其加载到struct appConfig 中。问题是,我需要在任何可能使用它的地方都可以修改这个结构,这意味着我必须使用互斥锁以避免内存损坏。
为了避免任何可能的指针问题和线程参数传递(这似乎有点痛苦),我决定使用我在 appConfig.h 中声明的全局变量:
struct appConfig config;
boost::mutex configMutex;
因此,我在使用它们的地方添加了 extern 声明:
appMain.cpp
extern struct appConfig config;
extern boost::mutex configMutex;
appServer.cpp
extern struct appConfig config;
extern boost::mutex configMutex;
appServer::appServer() {
return;
}
void appServer::operator()() {
configMutex.lock();
cout << "appServer thread." << endl;
configMutex.unlock();
}
appServer::~appServer() {
return;
}
在我看来,编译时不应该有任何问题,但我得到了这个不错的礼物:
appServer.o: In function `~appServer':
/usr/include/boost/exception/detail/exception_ptr.hpp:74: multiple definition of `configMutex'
appMain.o:/home/eax/CCITP/src/appMain.cpp:163: first defined here
appServer.o: In function `appServer':
/usr/include/boost/exception/exception.hpp:200: multiple definition of `config'
appMain.o:/usr/include/c++/4.6/bits/stl_construct.h:94: first defined here
collect2: ld returned 1 exit status
任何关于我如何解决这个问题的见解将不胜感激......
朱利安。
【问题讨论】:
-
建议:将互斥锁移到 appConfig 类/结构中,并让它对 getter 和 setter 方法执行锁定。强迫客户端记住锁定/解锁将是混乱且容易出错的。
-
这真是个好主意,我只需要使用一个类进行配置。解决后会尝试(无法解决这种让我好奇)
标签: c++ boost boost-thread