Skip to content

Instantly share code, notes, and snippets.

@vadz
Created March 31, 2014 12:05
Show Gist options
  • Save vadz/9890860 to your computer and use it in GitHub Desktop.
Save vadz/9890860 to your computer and use it in GitHub Desktop.
Dirty test for std::ostringstream::imbue() thread safety
#include <assert.h>
#include <locale.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <locale>
#include <sstream>
#include <string>
static const double TEST_NUM = 1.234567890123;
static const int NUM_ITER = 100000;
bool check_stream()
{
std::ostringstream os;
os.imbue(std::locale::classic());
os << TEST_NUM;
return os.str().find('.') != std::string::npos;
}
bool check_printf()
{
char buf[32];
snprintf(buf, sizeof(buf), "%g", TEST_NUM);
return strchr(buf, ',') != NULL;
}
void* thread1(void*)
{
for ( int n = 0; n < NUM_ITER; n++ )
assert(check_stream());
return NULL;
}
void* thread2(void*)
{
for ( int n = 0; n < NUM_ITER; n++ )
assert(check_printf());
return NULL;
}
int main()
{
setlocale(LC_ALL, "fr_FR");
if ( !check_stream() || !check_printf() )
return -1;
pthread_t t1, t2;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
void* ret;
return pthread_join(t1, &ret) && pthread_join(t2, &ret);
}
@mloskot
Copy link

mloskot commented Apr 5, 2014

% g++ -v
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~67/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~67/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
% g++ -Wall thrloc.cpp && ./a.out
Assertion failed: (check_printf()), function thread2, file thrloc.cpp, line 40.
[1]    67387 abort      ./a.out

It's somewhat reassuring that at least it is fixed in libc++:

% clang++ -v
Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.5.0
% clang++ -stdlib=libc++ -Wall thrloc.cpp && ./a.out
[...nothing...]

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