Skip to content

Boost:Interprocess

Shared memory, memory mapped files, process-shared mutexes, condition variables, containers and allocators.

scoped_lock

boost::mutex::scoped_lock은 객체가 살아있는 범위(scoped)내에 mutex를 사용한 Lock을 거는 객체이다. 사용방법은 아래와 같다:

#include <boost/thread.hpp>
#include <iostream>

using namespace std;
using namespace boost;

int nGlobalNum = 0;

void ThFunc(boost::mutex *pMutex)
{    
    int i = 0;

    for (i = 0; i < 10; i++)
    {
        boost::mutex::scoped_lock lock(*pMutex);
        cout << "thread (" << this_thread::get_id() << ") " << nGlobalNum << "\n";
        this_thread::sleep(boost::posix_time::millisec(500));
        nGlobalNum++;
    }
}  

int main(int argc, char **argv)
{
    boost::mutex mtx;  
    boost::thread_group tg;

    tg.create_thread(boost::bind(ThFunc, &mtx));
    tg.add_thread(new boost::thread(boost::bind(ThFunc, &mtx)));
    tg.join_all(); 

    return 0;
}

Favorite site