Skip to content

Instantly share code, notes, and snippets.

@ender233
Created July 26, 2017 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ender233/3e5edf7fc70429b29178b818e94f8667 to your computer and use it in GitHub Desktop.
Save ender233/3e5edf7fc70429b29178b818e94f8667 to your computer and use it in GitHub Desktop.
c++11多线程验证
#include <iostream>
#include <map>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;
class TestClass
{
public:
TestClass(){};
map<int,int> int_map;
};
class TestClass2
{
public:
TestClass2(TestClass *tc) {
tc1 = tc;
cout<<"TestClass2 get TestClass1, addr"<<tc1<<std::endl;
}
void Run() {
int i = 0;
while(true){
tc1->int_map.insert(make_pair(i,1));
cout<<"TestClass2:size of TestClass1 tc1->int_map size:"<<tc1->int_map.size()<<std::endl;
std::this_thread::sleep_for(2s);
i++;
}
}
private:
TestClass *tc1;
};
int main()
{
TestClass* tc1 = new TestClass();
printf("tc1 addr is %p!\n",tc1);
TestClass2* tc2 = new TestClass2(tc1);
std::thread t([&](){tc2->Run();});
t.detach();
do {
std::this_thread::sleep_for(1s);
cout<<"TestClass1:size of TestClass1 tc1->int_map size:"<<tc1->int_map.size()<<std::endl;
} while(true);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment