增加线程中的内存泄漏

时间:2013-04-15 09:03:37

标签: c++ boost memory-leaks

有人可以解释一下为什么代码的安静会导致内存泄漏吗?

Boost 1.49和boost-1.53​​给出相同的结果......

#include <boost/thread.hpp> 
#include <iostream> 
#include <vector> 
#include <cstdlib> 
#include <ctime> 

boost::mutex mutex; 
boost::condition_variable_any cond; 
std::vector<int> random_numbers; 

void fill() 
{ 
  std::srand(static_cast<unsigned int>(std::time(0))); 
  for (int i = 0; i < 3; ++i) 
  { 
    boost::unique_lock<boost::mutex> lock(mutex); 
    random_numbers.push_back(std::rand()); 
    cond.notify_all(); 
    cond.wait(mutex); 
  } 
} 

void print() 
{ 
  std::size_t next_size = 1; 
  for (int i = 0; i < 3; ++i) 
  { 
    boost::unique_lock<boost::mutex> lock(mutex); 
    while (random_numbers.size() != next_size) 
      cond.wait(mutex); 
    std::cout << random_numbers.back() << std::endl; 
    ++next_size; 
    cond.notify_all(); 
  } 
} 

int main() 
{ 
  boost::thread t1(fill); 
  boost::thread t2(print); 
  t1.join(); 
  t2.join(); 
}

这是valgrind输出:

  

valgrind --leak-check = full --show-reachable = yes ./a.out

     

== 3079 == Memcheck,一个内存错误检测器

     

== 3079 ==版权所有(C)2002-2011,以及Julian Seward等人的GNU GPL,

     

== 3079 ==使用Valgrind-3.7.0和LibVEX;用-h重新运行版权信息

     

== 3079 ==命令:./ a.out

     

== 3079 ==

     

val:535293148

     

val:1979778795

     

val:1888522902

     

== 3079 ==

     

== 3079 == HEAP SUMMARY:

     

== 3079 ==在退出时使用:1个块中的8个字节

     

== 3079 ==总堆使用量:16个分配,15个释放,1,732个字节分配

     

== 3079 ==

     

== 3079 = = 1个块中的8个字节仍可在丢失记录1中获得1

     

== 3079 ==在0x4C2B3F8:malloc(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so中)

     

== 3079 == by 0x4E45BF9:boost :: detail :: get_once_per_thread_epoch()(在/usr/local/lib/libboost_thread.so.1.53.0中)

     

== 3079 == by 0x4E3F861:_ZN5boost9call_onceIPFvvEEEvRNS_9once_flagET_.constprop.239(在/usr/local/lib/libboost_thread.so.1.53.0中)

     

== 3079 == by 0x4E3F978:boost :: detail :: get_current_thread_data()(在/usr/local/lib/libboost_thread.so.1.53.0中)

     

== 3079 == by 0x40A909:boost :: detail :: interruption_checker :: interruption_checker(pthread_mutex_t *,   pthread_cond_t *)(在/u00/system/workspace/shared_lock2/src/a.out中)

     

== 3079 == by 0x4E40502:boost :: thread :: join_noexcept()(在/usr/local/lib/libboost_thread.so.1.53.0中)

     

== 3079 == by 0x40ACAE:boost :: thread :: join()(在/u00/system/workspace/shared_lock2/src/a.out中)

     

== 3079 == by 0x4092B0:main(在/u00/system/workspace/shared_lock2/src/a.out)

     

== 3079 ==

     

== 3079 ==泄漏摘要:

     

== 3079 ==绝对丢失:0个块中的0个字节

     

== 3079 ==间接丢失:0个块中的0个字节

     

== 3079 ==可能丢失:0个块中的0个字节

     

== 3079 ==仍然可以访问:1个块中的8个字节

     

== 3079 ==抑制:0个块中的0个字节

     

== 3079 ==

     

== 3079 ==对于检测到的和抑制的错误计数,请重新运行:-v

     

== 3079 ==错误摘要:0个上下文中的0个错误(被抑制:2个来自2个)

此来源是来自http://en.highscore.de/cpp/boost/

的cpp book的一部分

0 个答案:

没有答案