Skip to content

Instantly share code, notes, and snippets.

@jmorrill
Last active August 29, 2015 14:22
Show Gist options
  • Save jmorrill/46783a2968bd2f64058d to your computer and use it in GitHub Desktop.
Save jmorrill/46783a2968bd2f64058d to your computer and use it in GitHub Desktop.
vs2013 vc++ bug?
/////VS 2013 /////
//////////////////
#include "stdafx.h"
#include <assert.h>
#include <thread>
#define __thread_local __declspec(thread)
const int some_int = 5;
struct _thread_local_data
{
std::thread::id thread_id;
int int_val;
void initialize()
{
thread_id = std::this_thread::get_id();
int_val = some_int;
}
};
__thread_local _thread_local_data data;
static int static_initialize()
{
data.initialize();
return 0;
}
static int val = static_initialize();
int _tmain(int argc, _TCHAR* argv[])
{
auto this_id = std::this_thread::get_id();
auto x = data.int_val;
assert(x == some_int);
//assert fails here
assert(this_id == data.thread_id);
return 0;
}
@mstrobel
Copy link

__thread_local _thread_local_data data;

_thread_local_data& ensure_thread_data() {
    if (data.int_val == 0)
        data.initialize();
    return data;
}

int _tmain(int argc, _TCHAR* argv[])
{
    auto data = ensure_thread_data();

    auto this_id = std::this_thread::get_id();
    auto x = data.int_val;

    assert(x == some_int);

    //assert fails here
    assert(this_id == data.thread_id);

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment