參考:html
2.C++11 併發指南二(std::thread 詳解)c++
4.C++11多線程(簡約但不簡單)github
5.github:編程
若是第一次接觸,直接看我給的參考便可,看過了以後,我把我以爲ok的重點總結在了下面多線程
-----------------------------------------------------筆記--------------------------------------------------併發
博客一:(一個簡單例程+makefile)app
#include <stdio.h> #include <stdlib.h> #include <iostream> // std::cout
#include <thread> // std::thread
void thread_task() { std::cout << "hello thread" << std::endl; } /* * === FUNCTION ========================================================= * Name: main * Description: program entry routine. * ======================================================================== */
int main(int argc, const char *argv[]) { std::thread t(thread_task); t.join(); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
all:Thread
CC=g++
CPPFLAGS=-Wall -std=c++11 -ggdb
LDFLAGS=-pthread
Thread:Thread.o
$(CC) $(LDFLAGS) -o $@ $^
Thread.o:Thread.cc
$(CC) $(CPPFLAGS) -o $@ -c $^
.PHONY:
clean
clean:
rm Thread.o Thread
博客二:(算是cplusplus官網給的.join()例子的擴充,挺好的)(也有其餘函數的官網連接)ide
#include <stdio.h> #include <stdlib.h> #include <chrono> // std::chrono::seconds
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
void thread_task(int n) { std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << "hello thread "
<< std::this_thread::get_id() << " paused " << n << " seconds" << std::endl; } /* * === FUNCTION ========================================================= * Name: main * Description: program entry routine. * ======================================================================== */
int main(int argc, const char *argv[]) { std::thread threads[5]; std::cout << "Spawning 5 threads...\n"; for (int i = 0; i < 5; i++) { threads[i] = std::thread(thread_task, i + 1); } std::cout << "Done spawning threads! Now wait for them to join\n"; for (auto& t: threads) { t.join(); } std::cout << "All threads joined.\n"; return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
結果是隔一秒打印一行
博客三:(有一個使用互斥量的例子,介紹了volatile關鍵字)
若是該線程是在同一類的某一成員函數當中被構造,則直接用this關鍵字代替便可。
這裏使用this指針代替實例化對象的地址
#include<iostream> #include<thread> #include<mutex> std::mutex mut; class A{ public: volatile int temp; A(){ temp=0; } void fun(int num){ int count=10; while(count>0){ mut.lock(); temp++; std::cout<<"thread_"<<num<<"...temp="<<temp<<std::endl; mut.unlock(); count--; } } void thread_run(){ std::thread t1(&A::fun,this,1); std::thread t2(&A::fun,this,2); t1.join(); t2.join(); } }; int main(){ A a; a.thread_run(); }
參考五:(hardware_concurrency)
檢測硬件併發特性,返回當前平臺的線程實現所支持的線程併發數目,但返回值僅僅只做爲系統提示(hint)。
#include <iostream> #include <thread> int main() { unsigned int n = std::thread::hardware_concurrency(); std::cout << n << " concurrent threads are supported.\n"; }
虛擬機設置爲2核,支持兩個線程併發