欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

boost share_ptr的使用例子

程序员文章站 2022-06-01 09:20:48
...
#include <stdio.h>
#include <iostream>
#include <string>
#include <map>
#include <boost/shared_ptr.hpp>

using namespace std;

//  g++ -c boost_share_ptr.cpp -I ../boost_1_66_0/ -L ../boost_1_66_0/stage/lib -lpthread -lboost_system


class TestObj
{
public:
	TestObj(int count)
	:m_nCount(count)
	{
		printf("%s %p \t%d\n", __FUNCTION__, this, m_nCount);
	}

	~TestObj()
	{
		printf("%s %p \t%d\n", __FUNCTION__, this, m_nCount);
	}

	void do_something()
	{
		printf("%s %p \t%d\n", __FUNCTION__, this, m_nCount);
	}
private:
	int m_nCount;
};


typedef std::map<int, boost::shared_ptr<TestObj> > _TestObjMap;
pthread_mutex_t m_mutex;
_TestObjMap TestObjMap;
void *StartThread(void *);
int main(int argc, char* argv[])
{
	printf("学习boost智能指针例子... \n");
	printf("期待结果:\n");
	printf("1.TestObj对象在main线程构造,在StartThread线程使用,使用完之后自动析构;\n");
	printf("2.count == 3的对象因为在main线程还在使用,所以在StartThread线程使用完也不析构\n");

	pthread_t m_thread;
	pthread_attr_t m_attr;

	pthread_attr_init(&m_attr);
	pthread_attr_setdetachstate(&m_attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&m_thread, &m_attr, StartThread, NULL);

	pthread_mutex_init(&m_mutex, NULL);
	int count = 0;
	boost::shared_ptr<TestObj> myTestObj100;
	while(1)
	{
		printf("count = %d\n", count);
		boost::shared_ptr<TestObj> myTestObj(new TestObj(count));

		do{
			pthread_mutex_lock(&m_mutex);
			TestObjMap.insert(std::make_pair<int, boost::shared_ptr<TestObj> >(count,myTestObj));
			pthread_mutex_unlock(&m_mutex);
		}while(0);

		if (count == 3)
		{
			printf("测试这个对象会不会被析构\n");
			myTestObj100 = myTestObj;
		}

		count++;
		sleep(1);
	}
	pthread_mutex_destroy(&m_mutex);
	return 0;
}

void *StartThread(void *)
{
	while(1)
	{
		do{
			pthread_mutex_lock(&m_mutex);
			_TestObjMap::iterator it = TestObjMap.begin();
			if(it != TestObjMap.end())
			{
				TestObjMap.erase(it);
				pthread_mutex_unlock(&m_mutex);

				it->second->do_something();
				break;
			}
			pthread_mutex_unlock(&m_mutex);
		}while(0);

		usleep(500);
	}
	return NULL;
}

[email protected]:~/opensource/sample$ ./boost_share_ptr 
学习boost智能指针例子... 
期待结果:
1.TestObj对象在main线程构造,在StartThread线程使用,使用完之后自动析构;
2.count == 3的对象因为在main线程还在使用,所以在StartThread线程使用完也不析构
count = 0
TestObj 0x14be140 0
do_something 0x14be140 0
~TestObj 0x14be140 0
count = 1
TestObj 0x14be160 1
do_something 0x14be160 1
~TestObj 0x14be160 1
count = 2
TestObj 0x14be140 2
do_something 0x14be140 2
~TestObj 0x14be140 2
count = 3
TestObj 0x14be160 3
测试这个对象会不会被析构
do_something 0x14be160 3
count = 4
TestObj 0x14be1c0 4
do_something 0x14be1c0 4
~TestObj 0x14be1c0 4
count = 5
TestObj 0x14be1e0 5
do_something 0x14be1e0 5
~TestObj 0x14be1e0 5
count = 6
TestObj 0x14be1c0 6
do_something 0x14be1c0 6