在共享指针里,有时也需要共享一个缓冲区,比如从网络收到数据,需要先放到缓冲区里,接着把这些数据发送给处理线程进行解包和处理。在这里就需要使用到两个线程里共享缓冲区的问题,因此比较好的解决方案,就采用引用计数的智能指针shared_array来解决,最为合适不过了。shared_array与shared_ptr具有相同的形式,使用和注意点也是相似的。具体的使用的例子如下:
// boost_005.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <memory.h>
#include <iostream>
#include <boost/shared_array.hpp>
//使用shared_array
void TestSharedArray(void)
{
//一般指针操作
const int nBufSize = 1024;
boost::shared_array< char > pFirst(new char[nBufSize]);
memset(pFirst.get(), 0x35, nBufSize);
std::cout << pFirst[0] << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
TestSharedArray();
system("PAUSE");
return 0;
}
本文介绍了一种在多线程环境下使用Boost库中的shared_array来实现缓冲区共享的方法。这种方式通过引用计数的智能指针机制有效地解决了缓冲区在不同线程间的共享问题,并提供了一个简单的示例代码说明其使用方法。
765

被折叠的 条评论
为什么被折叠?



