完美版的 多线程 STL 全局变量 崩溃例子

 #include "stdafx.h"

#define BOOST_AUTO_TEST_MAIN
#include
#include

#include
#include
#include

#include

boost::mutex mutex;
std::set gSet;

void add_gSet(int i)
{
printf("step1 写线程 gSet.insert\n");
gSet.insert(i);

printf(" 写线程 等待30毫秒,让读线程运行起来\n\n");
Sleep(30);

printf("step3 写线程 删除set里的元素\n\n");
gSet.erase(i);

}

void show_gSet()
{

int iPos=0;
std::set::iterator pos;
while(true)
{
printf("step2 读线程 Show\n");
for(pos= gSet.begin(); pos!= gSet.end(); ++pos)
{
//printf("gSet[%d]=%d ", iPos, *pos);
iPos++;

printf(" 读线程 等待100毫秒,让写线程erase \n\n");
Sleep(100);

printf("step4 读线程 下个循环周期,将要崩溃");
}
}
}

BOOST_AUTO_TEST_CASE(test_CText2Word)
{

BOOST_CHECK( true==true);
boost::thread_group threads;

printf("完美版的 多线程 STL 全局变量 崩溃例子 \n");
printf("mafeitao www.18ie.com\n\n");
threads.create_thread( boost::bind(add_gSet,1));

//确保写线程先运行
Sleep(10);

threads.create_thread( boost::bind(show_gSet));

threads.join_all();

}

发表评论


0.029 sec