valgrind

时间:2017-03-07 02:34:14

标签: c++ multithreading c++11

如下所示的简单线程程序显示了valgrind中的数据竞争:

#include <iostream>
#include <thread>

void fun(void){
    int a = 0;
}

int main(){
    std::thread th1(fun);
    th1.join();
    return 0;
}

错误:

----------------------------------------------------------------
==20753== 
==20753== Possible data race during write of size 8 at 0x60BC88 by thread #1
==20753== Locks held: none
==20753==    at 0x401B57: std::shared_ptr<std::thread::_Impl_base>::~shared_ptr() (shared_ptr.h:93)
==20753==    by 0x401E5F: std::thread::thread<void (&)()>(void (&)()) (thread:137)
==20753==    by 0x4016DA: main (testmv.cpp:9)
==20753== 
==20753== This conflicts with a previous write of size 8 by thread #2
==20753== Locks held: none
==20753==    at 0x401B57: std::shared_ptr<std::thread::_Impl_base>::~shared_ptr() (shared_ptr.h:93)
==20753==    by 0x401B9B: std::thread::_Impl_base::~_Impl_base() (in /home/jahid/Git/Github/jpcre2/jpcre2/src/a.out)
==20753==    by 0x403B71: std::thread::_Impl<std::_Bind_simple<void (*())()> >::~_Impl() (in /home/jahid/Git/Github/jpcre2/jpcre2/src/a.out)
==20753==    by 0x4040F0: void __gnu_cxx::new_allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >::destroy<std::thread::_Impl<std::_Bind_simple<void (*())()> > >(std::thread::_Impl<std::_Bind_simple<void (*())()> >*) (new_allocator.h:124)
==20753==    by 0x403FFA: void std::allocator_traits<std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > > >::destroy<std::thread::_Impl<std::_Bind_simple<void (*())()> > >(std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >&, std::thread::_Impl<std::_Bind_simple<void (*())()> >*) (alloc_traits.h:542)
==20753==    by 0x403D8D: std::_Sp_counted_ptr_inplace<std::thread::_Impl<std::_Bind_simple<void (*())()> >, std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >, (__gnu_cxx::_Lock_policy)2>::_M_dispose() (shared_ptr_base.h:531)
==20753==    by 0x4EF8D14: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==20753==    by 0x4C34DB6: ??? (in /usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so)
==20753==  Address 0x60bc88 is 8 bytes inside data symbol "__gcov0._ZNSt10shared_ptrINSt6thread10_Impl_baseEED2Ev"

该程序使用g ++(5.4.0)编译:

g++ -O0 -ggdb3 -fprofile-arcs -ftest-coverage -std=c++11 -pthread testmv.cpp

并使用helgrind工具( valgrind 3.11.0 )进行测试:

valgrind --tool=helgrind ./a.out

我在这里做错了吗?

0 个答案:

没有答案