happybirthdaytoyou

代码:

  // boost库 条件变量 使用测试 

#include <iostream>
#include <boost/thread.hpp>
using namespace std;

boost::condition_variable cond;        //关联多个线程的条件变量
boost::mutex mutex;             //保护共享资源的互斥体
int k=0;                    //作为共享资源
 
void func1(const int &id)
{
    boost::unique_lock<boost::mutex> lock(mutex); //   m->lock();

    cout << "thread #hi#" << id << endl;

    #if 1
        static int i = 0;
        if(i++ == 1) // 第二个线程执行本函数,我就上锁两次,应该会锁死第二个线程自身。
            boost::unique_lock<boost::mutex> lock_again(mutex); // m->lock();
    #endif

        cout << "func1, k = " << k << endl;
    while(k<5)
    {
        cout << "thread #" << id << " : k<5, waiting..." << endl;
        cond.wait(lock); 
    }
    cout << "thread #" << id << " : now k>5, printing..." << endl;
}
void func2(const int &id)
{
    cout << "thread #hi#" << id << endl;
    boost::unique_lock<boost::mutex> lock(mutex);
        cout << "func2, k = " << k << endl;
    cout << "thread #" << id << " : k will be changed..." << endl;
    k+=5; // 模拟操作共享资源 , 在锁的保护下,此时生产者是独占性操作共享资源
    
    cond.notify_all();//唤醒所有的等待线程
    //cond.notify_one();//只会唤醒一个等待线程
}


int main()
{
    // 这个线程应该会顺利执行完毕
    boost::thread t1(func1, 1);
        boost::this_thread::sleep(boost::posix_time::seconds(1));

    // 这个线程内,上锁两次,应该会锁死本线程
    boost::thread t2(func1, 2);

    // 那么主线程还能继续向下执行吗  实测说话
    // 实测能继续向下执行,
    //实测,使用boost库的互斥锁和linux上的一模一样
        cout << "go on" << endl;
        boost::this_thread::sleep(boost::posix_time::seconds(1));

    // 同理,也锁死
    boost::thread t3(func2, 3);

    t1.join();
    t2.join();
    t3.join();
        cout << "---end---" << endl;
    return 0;
}

makefile:

.PHONY: DOIT

DOIT:
    mips-linux-gnu-g++ -I.  thread_pack.cpp -L./lib  -lboost_thread -lboost_system -o boost_app

实测结论: 使用基于boost库的互斥锁、条件变量,和基于linux的原生API,效果一模一样。 

 

 

 

 

 

 

 

 

.

相关文章:

相关资源