编译代码如下
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
struct Test
{
Test() { std::cout << " Test::Test()\n"; }
~Test() { std::cout << " Test::~Test()\n"; }
};
//线程函数
void thr(std::shared_ptr<Test> p)
{
//线程暂停1s
std::this_thread::sleep_for(std::chrono::seconds(1));
//赋值操作, shared_ptr引用计数use_cont加1(c++11中是原子操作)
std::shared_ptr<Test> lp = p;
{
//static变量(单例模式),多线程同步用
static std::mutex io_mutex;
//std::lock_guard加锁
std::lock_guard<std::mutex> lk(io_mutex);
std::cout << "local pointer in a thread:\n"
<< " lp.get() = " << lp.get()
<< ", lp.use_count() = " << lp.use_count() << '\n';
}
}
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
//使用make_shared一次分配好需要内存
std::shared_ptr<Test> p = std::make_shared<Test>();
//std::shared_ptr<Test> p(new Test);
std::cout << "Created a shared Test\n"
<< " p.get() = " << p.get()
<< ", p.use_count() = " << p.use_count() << '\n';
//创建三个线程,t1,t2,t3
//形参作为拷贝, 引用计数也会加1
//thr(p);
int n = 0;
//f1(5);
std::thread t2(f1, n + 1); // pass by value
//std::thread t1(thr,p);
//std::thread t1(thr, p), t2(thr, p), t3(thr, p);
// std::cout << "Shared ownership between 3 threads and released\n"
// << "ownership from main:\n"
// << " p.get() = " << p.get()
// << ", p.use_count() = " << p.use_count() << '\n';
// //等待结束
// t1.join(); t2.join(); t3.join();
// std::cout << "All threads completed, the last one deleted\n";
return 0;
}
编译命令如下:
g++ shared_ptr2.cpp
遇到问题如下:
error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options. #error This file requires compiler and library support \
解决方式如下:
将编译命令改为,g++ -std=c++11 shared_ptr2.cpp
出现另一个报错:
/tmp/ccoN94id.o: In function `std::thread::thread<void (&)(int), int>(void (&)(int), int&&)':
shared_ptr2.cpp:(.text._ZNSt6threadC2IRFviEJiEEEOT_DpOT0_[_ZNSt6threadC5IRFviEJiEEEOT_DpOT0_]+0x93): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
解决方式如下:
将编译命令改为,g++ -std=c++11 -pthread shared_ptr2.cpp