本例是Modern CPP Concurrency的一个例子,他简单的使用了线程的第二个功效,分离concern。
本例使用主线程绘制界面元素。使用4个分离的线程更新四个圆的颜色。
不同线程干不同的活,互不干扰。
程序非常简单,使用了SFML库,需要在conan中链接。
代码如下,
conanfile.txt
[requires]
boost/1.72.0
sfml/2.6.1
[generators]
cmake
CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(9_example_parallel_sfml)
set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:/usr/local/lib/pkgconfig/")
set ( CMAKE_CXX_FLAGS "-pthread")
set(CMAKE_CXX_STANDARD 17)
add_definitions(-g)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
include_directories(${INCLUDE_DIRS})
LINK_DIRECTORIES(${LINK_DIRS})
file( GLOB main_file_list ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
foreach( main_file ${main_file_list} )
file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${main_file})
string(REPLACE ".cpp" "" file ${filename})
add_executable(${file} ${main_file})
target_link_libraries(${file} ${CONAN_LIBS} pthread)
endforeach( main_file ${main_file_list})
main.cpp
#include <iostream>
#include <thread>
#include "SFML/Graphics.hpp"
#include <atomic>
#include <vector>
#include <functional>
#include <chrono>
#include <algorithm>
#include <memory>
std::vector<int> grid;
std::vector<std::unique_ptr<sf::Shape>> shapes;
bool is_running = true;
void update_grid(int x, int y) {
while(is_running) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
grid[y * 2 + x] = rand() % 4;
}
}
int main(int argc, char* argv[]) {
grid.reserve(4);
std::fill(grid.begin(), grid.end(), 0);
for(int x=0; x<2; ++x) {
for(int y=0; y<2; ++y) {
shapes.push_back(std::make_unique<sf::CircleShape>(100.0f));
}
}
std::vector<std::thread> threads;
for(int x=0; x<2; ++x) {
for(int y=0; y<2; ++y) {
threads.push_back(std::thread(update_grid, x, y));
}
}
sf::RenderWindow window(sf::VideoMode(400, 400), "SFML with C++ Threads");
while(window.isOpen() && is_running) {
sf::Event event;
while(window.pollEvent(event)) {
if(event.type == sf::Event::Closed) {
window.close();
is_running = false;
}
}
window.clear();
for(int x=0; x<2; ++x) {
for(int y=0; y<2; ++y) {
shapes[y * 2 + x]->setPosition(x*200, y*200);
if(0 == grid[y * 2 + x]) {
shapes[y * 2 + x]->setFillColor(sf::Color::Red);
} else if(1 == grid[y * 2 + x]) {
shapes[y * 2 + x]->setFillColor(sf::Color::Green);
} else if(2 == grid[y * 2 + x]) {
shapes[y * 2 + x]->setFillColor(sf::Color::Blue);
} else if(3 == grid[y * 2 + x]) {
shapes[y * 2 + x]->setFillColor(sf::Color::White);
}
}
}
for(auto& shape: shapes) {
window.draw(*shape);
}
window.display();
}
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
return EXIT_SUCCESS;
}
程序效果如下,

网友评论