2012-01-12 73 views
0

我正在实现一个简单的线程应用程序,其中有一个服务器线程和一个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 

对我怎么能解决这个问题的任何见解将不胜感激...

朱利安。

+1

建议:在appConfig类/结构中移动互斥锁,并让它对getter和setter方法执行锁定。强迫客户记住锁定/解锁将变得混乱和容易出错。 – Lalaland 2012-01-12 04:29:11

+0

这真是一个好主意,我只需要使用一个类来进行配置。这个解决之后会试试(不能解决这种好奇) – 2012-01-12 04:32:44

回答

3

这实际上并不是一个提升问题:你已经在头文件中声明了一个全局变量,因此这两个编译单元都在全局范围内定义了这个变量,从而导致了多个定义。

在头文件中声明它extern,并在一个.cpp文件中定义它应该工作。

+0

它当时做了,对延迟接受抱歉。 – 2012-01-17 02:41:44