C++ 11 thread[WINDOWS/LINUX]( C++ 11之後有了std::thread函式庫,需要引入的標頭檔: )

C++ 11 thread[WINDOWS/LINUX]( C++ 11之後有了std::thread函式庫,需要引入的標頭檔: )

C++ 11 thread[WINDOWS/LINUX]( C++ 11之後有了std::thread函式庫,需要引入的標頭檔: <thread> )


資料來源: https://medium.com/@chingi071/%E5%A4%9A%E5%9F%B7%E8%A1%8C%E7%B7%92-c-thread-9f6e37c7cf32


GITHUB: https://github.com/jash-git/CPP11_thread

範例測試環境: VC++(2015) / CB20.03


PS.LINUX gcc/g++  c++11編譯的語法
    g++ -g -Wall -std=c++11 main.cpp
    gcc -g -Wall -std=c11 main.cpp


CB設定


code ~ 範例03[C++ thread lock 共用變數]

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

/*
std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5 ’(seconds)
std::this_thread::sleep_for(std::chrono::milliseconds(5)); // sleep 5 ²@¬í(milliseconds)
std::this_thread::sleep_for(std::chrono::microseconds(5)); // sleep 5 ·L¬í(microseconds)
std::this_thread::sleep_for(std::chrono::nanoseconds(5)); // sleep 5 ¯Ç¬í(nanoseconds)
*/
mutex mu;
int gintCount = 0;
void thread_job(int intData)
{
	mu.lock();
	gintCount += intData;
	std::this_thread::sleep_for(std::chrono::seconds(intData-1));
	cout << "thread  " << intData <<" finish..."<< endl;
	mu.unlock();
}
void Pause()
{
	printf("Press Enter key to continue¡K");
	fgetc(stdin);
}

int main()
{
	thread cthread[10];

	cout << "gintCount is " << gintCount << endl;
	for (int i = 0; i < 10; i++)
	{
		cthread[i] = thread(thread_job, i+1);
	}
	for (int i = 0; i < 10; i++)
	{
		cthread[i].join();
	}
	cout << "gintCount is " << gintCount << endl;
	Pause();
	return 0;

}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *