小编rgo*_*ble的帖子

std :: call_once是可重入的还是线程安全的?

std :: call_once 是线程安全的,但是它也可以重入吗?

我使用VS2012(Debug和Release)进行的测试表明,std::call_once从单个线程递归调用是可以的,但如果调用是在不同的线程上进行的,则会导致死锁.这是一个已知的限制std::call_once吗?

#include "stdafx.h"

#include <iostream>
#include <mutex>
#include <thread>

void Foo()
{
    std::cout << "Foo start" << std::endl;

    std::once_flag flag;
    std::call_once( flag, [](){
        std::cout << "Hello World!" << std::endl;
    });

    std::cout << "Foo end" << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Single threaded Works
    {
        std::once_flag fooFlag;
        std::call_once( fooFlag, Foo);      
    }

    // Works
    // Threaded version, join outside call_once
    {
        std::once_flag fooFlag;
        std::thread t;
        std::call_once( fooFlag, [&t](){
            t = …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

7
推荐指数
1
解决办法
2421
查看次数

标签 统计

c++ ×1

c++11 ×1