c++线程
概述
linux下多线程需要使用pthread库,通过 #include<thread>包含所需的函数及方法;C11才开始引入线程的概念
CMake
需要连接到pthread库,target_link_libraries(threads pthread)
cmake_minimum_required(VERSION 3.5.1)
project(threads)
add_executable(threads threads.cpp)set(CMAKE_SYSTEM_NAME Linux)SET(CMAKE_CXX_FLAGS "--std=c++11")
target_link_libraries(threads pthread)
测试代码
#include <chrono>
#include <iostream>
#include <thread>void worker(int index) {for (int i = 0; i < 10; i++) {std::cout << "Worker " << index << " begins" << std::endl;std::this_thread::sleep_for(std::chrono::milliseconds(50));std::cout << "Worker " << index << " ends" << std::endl;std::this_thread::sleep_for(std::chrono::milliseconds(1));}
}int main() {std::thread worker1(worker, 1);std::thread worker2(worker, 2);worker1.join();worker2.join();std::cout << "Done" << std::endl;
}
我公司承接各类技术服务,主要聚焦于:stm32、单片机、嵌入式、QT应用开发、Web+Python+Django应用开发。欢迎合作。
