這幾天,陸續在網上見到了幾個高中的好同學,發現曾經很優秀的他們,現在對游戲竟然都上癮了,由于高中管理嚴格,所以沒有機會出去玩,到了大學,
可謂是天時地利人和,控制不住自己,瘋玩。工作混得一塌糊涂,卻不忘游戲,可嘆!再過上10年,人和人就會是天壤之別,希望他們早點清醒自己的頭腦,別在沉浸在游戲中了,是該奮斗的時候了!
成員模板的定義超出了類的范圍。Visual C++ 的一個限制是,成員模板的定義必須完全位于封閉類內
像下面的好用工具函數就無法使用:
string format_string(const char *fmt, ...)
{
/* Guess we need no more than 512 bytes. */
int n, size = 512;
char *p;
va_list ap;
if ((p = (char*)malloc (size)) == NULL)
return "";
while (1)
{
/* Try to print in the allocated space. */
va_start(ap, fmt);
n = vsnprintf (p, size, fmt, ap);
va_end(ap);
/* If that worked, return the string. */
if (n > -1 && n < size)
{
string str(p);
if(p)
free(p);
return str;
}
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if ((p = (char*)realloc (p, size)) == NULL)
{
if(p)
free(p);
return "";
}
}
}
boost提供的message queue發送接口有send,try_send,timed_send,接收接口有receive,try_receive,timed_receive,其它接口有get_max_msg,get_max_msg_size,get_num_msg,remove。學習難度不高。下面測試一下send的發送速度:
測試代碼:
#define BOOST_ALL_DYN_LINK
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/format.hpp>
#include <boost/progress.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace boost;
using namespace boost::interprocess;
#define MAX_MSG_COUNT 50000
#define MAX_MSG_SIZE 1024
int main ()
{
try{
//Erase previous message queue
message_queue::remove("message_queue");
//Create a message_queue.
message_queue mq
(create_only //only create
,"message_queue" //name
,MAX_MSG_COUNT //max message number
,MAX_MSG_SIZE //max message size
);
{
progress_timer pt;//記錄時間,多方便!
for(int i = 0; i < 5000; ++i)//可靈活調整i的大小
{
std::string msg = str(format("hello world %d") % i);
bool bRet = mq.send(msg.c_str(),msg.size(),0);
}
}
}
catch(interprocess_exception &ex)
{
message_queue::remove("message_queue");
std::cout << ex.what() << std::endl;
return 1;
}
//message_queue::remove("message_queue");
return 0;
}
我的測試結果如下:
500 0.16s
1000 0.41/0.50 -->表示測了2次,第一次0.41s,第二次0.50s,下同
5000條 5.88s/6.16
10000 22.81s/22.34
20000 87.92/91.22
最后簡單總結一下boost message queue:
優點:速度還不錯,接口學習起來簡單,方便易用
缺點:我在windows下測試,當一直在寫隊列時,用ctrl + c中斷,然后用另一進程讀讀隊列,讀操作時阻塞。單步跟蹤發現
是阻塞在interprocess_mutex::lock加鎖的操作上,健壯程度遠不如msgsnd,msgrcv系列,及msmq,該缺點比較致命。目前沒有測試linux下的情況。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.wait();
std::cout << "Hello, world!\n";
return 0;
}