boost thread

mutex
用法和posix的mutex一样
#include <iostream>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

int main()
{

    boost::mutex mu;
    try{
	mu.lock();
	std::cout<<"some operation"<<std::endl;
	mu.unlock();
    }
    catch(std::exception& e){
    	std::cout << e.what() << std::endl;
    	mu.unlock();
    }
}
lock_guard类构造时自动自动锁定互斥量,析构时自动释放互斥量,使用lock_guard类的内部类型scoped_lock
#include <iostream>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

int main()
{
	boost::mutex mu;
    try{
    	boost::mutex::scoped_lock lock(mu);
	std::cout<<"some operation"<<std::endl;
    }
    catch(std::exception& e){
    	std::cout << e.what() << std::endl;
    	
    }
}

启动线程
#include <iostream>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

boost::mutex mu;
void printing(const std::string &str)
{
    for(int i=0;i<10;i++)
    {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        boost::mutex::scoped_lock lock(mu);
        std::cout<<"some op"<<std::endl;
        std::cout<<str<<std::endl;
    }
}
int main()
{

    try{
        boost::thread t1(printing,"hello");
        t1.join();
    }
    catch(std::exception& e){
        std::cout << e.what() << std::endl;
        mu.unlock();
    }
}

中断线程
#include <iostream>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

boost::mutex mu;
void printing(const std::string &str)
{

    try {

        for(int i=0;i<10;i++)
        {
            boost::this_thread::sleep(boost::posix_time::seconds(3));
            //sleep(5);
            boost::mutex::scoped_lock lock(mu);
            std::cout<<"some op"<<std::endl;
            std::cout<<str<<std::endl;
        }
    } catch (boost::thread_interrupted& e) {
            std::cout<<"thread_interrupted"<<std::endl;
    }

}
int main()
{

    try{
        boost::thread t1(printing,"hello");
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        //t1.detach();
        t1.interrupt();
        t1.join();
    }
    catch(std::exception& e){
        std::cout << e.what() << std::endl;

    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值