草庐IT

C++11 静态局部变量和线程

coder 2024-02-11 原文

对于创建/使用 std::thread 的类,静态局部变量是否安全?

因为当我使用这样的东西时:

logger& logger::get_instance(void)
{
    static logger lg;
    return lg;
}

并尝试退出(强制关闭)可执行文件,它崩溃/不正确退出(Visual Studio 2012 调试器甚至崩溃)。

当我不这样做时,程序会在我强制关闭时正常退出。

这是崩溃时的堆栈调用

        ntdll.dll!77c10dbd()    Unknown
        [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll] 
        ntdll.dll!77b7bfdc()    Unknown
        kernel32.dll!75b55bab() Unknown
    >   msvcr110d.dll!__crtCreateThreadpoolWait(void (_TP_CALLBACK_INSTANCE *, void *, _TP_WAIT *, unsigned long) * pfnwa, void * pv, _TP_CALLBACK_ENVIRON_V1 * pcbe) Line 569  C
        msvcr110d.dll!Concurrency::details::RegisterAsyncWaitAndLoadLibrary(void * waitingEvent, void (_TP_CALLBACK_INSTANCE *, void *, _TP_WAIT *, unsigned long) * callback, void * data) Line 675    C++
        msvcr110d.dll!Concurrency::details::ExternalContextBase::PrepareForUse(bool explicitAttach) Line 120    C++
        msvcr110d.dll!Concurrency::details::ExternalContextBase::ExternalContextBase(Concurrency::details::SchedulerBase * pScheduler, bool explicitAttach) Line 52 C++
        msvcr110d.dll!Concurrency::details::SchedulerBase::GetExternalContext(bool explicitAttach) Line 1579    C++
        msvcr110d.dll!Concurrency::details::SchedulerBase::AttachExternalContext(bool explicitAttach) Line 1527 C++
        msvcr110d.dll!Concurrency::details::SchedulerBase::CreateContextFromDefaultScheduler() Line 569 C++
        msvcr110d.dll!Concurrency::details::SchedulerBase::CurrentContext() Line 402    C++
        msvcr110d.dll!Concurrency::details::LockQueueNode::LockQueueNode(unsigned int timeout) Line 616 C++
        msvcr110d.dll!Concurrency::critical_section::lock() Line 1017   C++
        msvcp110d.dll!mtx_do_lock(_Mtx_internal_imp_t * * mtx, const xtime * target) Line 65    C++
        msvcp110d.dll!_Mtx_lock(_Mtx_internal_imp_t * * mtx) Line 144   C++
        escobar.exe!std::_Mtx_lockX(_Mtx_internal_imp_t * * _Mtx) Line 68   C++
        escobar.exe!std::_Mutex_base::lock() Line 43    C++
        escobar.exe!std::unique_lock<std::mutex>::unique_lock<std::mutex>(std::mutex & _Mtx) Line 228   C++
        escobar.exe!escobar::utilities::blocking_queue<escobar::logging::log_message *>::interrupt() Line 71    C++
        escobar.exe!escobar::logging::log_worker::~log_worker() Line 17 C++
        escobar.exe!escobar::logging::log_worker::`scalar deleting destructor'(unsigned int)    C++
        escobar.exe!escobar::logging::logger::close() Line 72   C++
        escobar.exe!escobar::logging::logger::~logger() Line 27 C++
        escobar.exe!`escobar::logging::logger::get_instance'::`2'::`dynamic atexit destructor for 'lg''()   C++
        msvcr110d.dll!doexit(int code, int quick, int retcaller) Line 585   C
        msvcr110d.dll!_cexit() Line 410 C
        msvcr110d.dll!__CRTDLL_INIT(void * hDllHandle, unsigned long dwReason, void * lpreserved) Line 296  C
        msvcr110d.dll!_CRTDLL_INIT(void * hDllHandle, unsigned long dwReason, void * lpreserved) Line 210   C
        ntdll.dll!77bb2846()    Unknown
        ntdll.dll!77bb2893()    Unknown
        ntdll.dll!77bc09c8()    Unknown
        ntdll.dll!77bc08ad()    Unknown
        KernelBase.dll!75525bbb()   Unknown
        KernelBase.dll!75525c51()   Unknown
        kernel32.dll!75b58543() Unknown
        ntdll.dll!77bbac69()    Unknown
        ntdll.dll!77bbac3c()    Unknown

这里有几个函数

log_worker::~log_worker(void)
{
    this->queue.interrupt();
    service.join();
}

void log_worker::run(void)
{
    while (true)
    {
        log_message* msg;
        if (this->queue.dequeue(msg) == false)
            break;

        this->lg->print_log_message(msg);

        delete msg;
    }
}


    bool dequeue(T& item)
    {
        std::unique_lock<std::mutex> lock(m);

        // handles spurious wakeups
        while (!this->data_available && !this->interrupted)
            cv.wait(lock);

        if (this->interrupted)
            return false;

        item = std::move(this->front());
        this->pop();
        if (this->empty())
            this->data_available = false;
        return true;
    }

    void interrupt(void)
    {
        std::unique_lock<std::mutex> lock(m);
        this->interrupted = true;
        cv.notify_all();
        printf("notified threads...\n");
    }

最佳答案

看起来你有一个分离的线程 SchedulerBase(可以是任何仍然使用 logger 的调度线程),它在你的应用程序时仍在运行被停止并且 logger 被破坏导致崩溃。

And log_worker is dynamically allocated in the logger class.

  • 您需要确保在销毁logger 之前,所有使用logger 实例的线程都已正确关闭
  • 删除记录器析构函数中的 log_worker

关于C++11 静态局部变量和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14669983/

有关C++11 静态局部变量和线程的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  5. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  6. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  7. ruby - Rack:如何将 URL 存储为变量? - 2

    我正在编写一个简单的静态Rack应用程序。查看下面的config.ru代码:useRack::Static,:urls=>["/elements","/img","/pages","/users","/css","/js"],:root=>"archive"map'/'dorunProc.new{|env|[200,{'Content-Type'=>'text/html','Cache-Control'=>'public,max-age=6400'},File.open('archive/splash.html',File::RDONLY)]}endmap'/pages/search.

  8. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  9. ruby - 安装libv8(3.11.8.13)出错,Bundler无法继续 - 2

    运行bundleinstall后出现此错误:Gem::Package::FormatError:nometadatafoundin/Users/jeanosorio/.rvm/gems/ruby-1.9.3-p286/cache/libv8-3.11.8.13-x86_64-darwin-12.gemAnerroroccurredwhileinstallinglibv8(3.11.8.13),andBundlercannotcontinue.Makesurethat`geminstalllibv8-v'3.11.8.13'`succeedsbeforebundling.我试试gemin

  10. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

随机推荐