【问题标题】:Boost thread resources and mutexes提升线程资源和互斥锁
【发布时间】: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


【解决方案1】:

这本身并不是一个真正的提升问题:您已经在头文件中声明了一个全局变量,因此在两个编译单元的全局范围内定义,导致多个定义。

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

【讨论】:

    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2011-03-09
    • 2013-01-31
    • 2018-10-06
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多