今天有时间了,于是决定写点boost使用的东西,这里主要讲下其中thread库和signal库的使用,代码采用最简单的方式编写,不带任何其他的杂质,旨在教会大家两个库的简单使用。好了贴代码:
#include <boost/thread.hpp>
#include <boost/signal.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <memory>
#include <iostream>
class world :
public boost::signals::trackable
{
public:
static void a() {}
void hello(int a) const
{
std::cout << a << std::endl;
std::cout << "Hello, world!" << std::endl;
}
};
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
void thread()
{
for (int i = 0; i < 5; ++i)
{
wait(1);
std::cout << i << std::endl;
}
}
class HelloWorld
{
public:
void hello(const std::string& str)
{
std::cout << str << std::endl;
}
};
int main()
{
boost::thread t(thread);
t.join();
boost::signal<void(int) > s;
{
std::auto_ptr<world> w(new world());
std::auto_ptr<world> jjf(new world());
s.connect(boost::bind(&world::hello, w.get(),_1));
w->a();
std::cout << "in { } " << s.num_slots() << std::endl;
s(3);
}
std::cout << "out { } " << s.num_slots() << std::endl;
s(4);
HelloWorld obj;
boost::thread thrd(boost::bind(&HelloWorld::hello, &obj, "Hello World, I'm a thread!"));
thrd.join();
system("pause");
return 0;
}
免得被人说无图无真相,然后附上程序截图:
好了进行简单的说明:bind这个上一节已经说过了,这里就不进行讲解了,然后让我们快速查看一下信号槽,这个就是一个简单的信号量的声明,说明这个signal的处理函数是一个void类型的,接收一个为int类型的参数,我们在{}中声明两个智能指针的变量体,然后对信号槽进行处理函数的绑定,绑定之后,我们就立刻触发下这个事件,然后看看结果,并且输出信号槽中处理函数的个数。
当然最后再次调用一个输出信号槽的个数只是为了验证对象消失后会不会悲剧,然后最后一个调用thread表示如何给线程中传入参数!当然boost的线程如此简单,以至于让我感觉这是在写线程代码?!今晚看此文章的人,你太苦逼了表示,从13码到14呵呵!