CMakeLists.txt 添加Boost库

倖福魔咒の 提交于 2019-12-31 23:20:41

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();
}

结果执行如下:

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!