CMakeLists.txt 添加Boost库

Demo描述:使用boost::mutex 锁机制,打印两个线程的输出。

源码如下:

#include <iostream>

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

boost::mutex mutex;

void print_block(int n, char c)
{
    // critical section (exclusive access to std::cout signaled by locking mtx):
    mutex.lock();
    for (int i = 0; i < n; ++i)
    {
        std::cout << c;
    }
    std::cout << '\n';
    mutex.unlock();
}

int main(int argc, char* argv[])
{
    boost::thread thread1(&print_block, 300, '*');
    boost::thread thread2(&print_block, 300, '$');

    thread1.join();
    thread2.join();

    return 0;
}

CmakeLists.txt内容如下:

# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(mutex_project)

SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11")

## System dependencies are found with CMake's conventions
find_package(Boost REQUIRED COMPONENTS
    thread
)

if(NOT Boost_FOUND)
    message("NOT found Boost")
endif()

include_directories(${Boost_INCLUDE_DIRS})
# Declare the executable target built from your sources
add_executable(${PROJECT_NAME} src/main.cpp)
target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES})

执行输出:

------------------------------------------------------------------------更新-------------------------------------------------------------------------------------------

如果去除lock

void print_block(int n, char c)
{
    // critical section (exclusive access to std::cout signaled by locking mtx):
    //mutex.lock();
    for (int i = 0; i < n; ++i)
    {
        std::cout << c;
    }
    std::cout << '\n';
    //mutex.unlock();
}

结果执行如下:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值