// CppTest.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//
#include <iostream>
#include <thread>
#include <windows.h>
#include <string>
#include <mutex>
#include <functional>
#include <chrono>
int number = 0;
std::mutex mtx;
void fun1()
{
for (int i = 0; i < 1000; i++)
{
std::unique_lock<std::mutex> lck(mtx);
number++;
std::cout << number << std::endl;
}
}
void fun2()
{
for (int i = 0; i < 1000; i++)
{
std::unique_lock<std::mutex> lck(mtx);
number--;
std::cout << number << std::endl;
}
}
class demo
{
public:
demo() {}
~demo() {}
public:
void print(std::string msg)
{
std::unique_lock<std::mutex> lck(mtx);
//for (int i = 0; i < (int)msg; i++)
//{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << msg << std::endl;
//}
}
void threadPrintMsg(std::string n)
{
std::function<void(std::string)> fun;
fun = std::bind(&demo::print, this,std::placeholders::_1); //綁定類成員函數
//fun = std::bind(&demo::print, this,std::placeholders::_1,std::placeholders::_2);//多個參數
std::thread *th = new std::thread(fun,n);//往線程中傳參
//std::thread *th = new std::thread(fun, n1,n2);//多參數
}
};
int main()
{
std::function<void(void)>f; //指向返回值爲空,參數列表爲空的函數
std::function<int(double, double)> f2;//指向返回值爲int,參數列表爲(double,double)的函數
demo* de = new demo();
std::string msg = "aaaa";
de->threadPrintMsg(msg);
f = fun1;//綁定函數
std::thread th1(f);
std::thread th2(fun2);
th1.join();//等待線程執行完成後再執行後續代碼
th2.join();
//th1.detach();
//th2.detach(); //直接運行主線程
system("pause");
return 0;
}