今天关注了下最新的C++标准,并试用了下std::thread,lock_guard等功能,还是不错的。
对于std::thread要join/detach,不然会有异常。
另外当使用socket时网络函数bind应该使用::bind表明是全局的命名空间
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <vector>
using namespace std;
int globalCount = 10;
std::mutex g_mutex;
void fun1(int n)
{
std::lock_guard<std::mutex> g(g_mutex);
globalCount++;
n++;
thread::id i = std::this_thread::get_id();
cout << i << " fun1: " << n << endl;
}
void fun2(int& n)
{
n++;
thread::id i = std::this_thread::get_id();
cout << i << " fun1: " << n << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n1 = 100;
int n2 = 100;
std::thread t1(fun1, n1);
std::thread t2(fun2, std::ref(n2));
t1.join();
t2.join();
cout << "Main:" << n1 << " , " << n2 << endl;
std::vector<std::thread*> threadList;
for(int i = 0; i < 20; i++)
{
std::thread* t = new std::thread(fun1, i);
threadList.push_back(t);
}
for(int i = 0; i < 20; i++)
{
threadList[i]->join();
}
std::this_thread::sleep_for(std::chrono::seconds(1));
cout << endl << globalCount << endl;
cout << "press any key to exit..." << endl;
char c;
cin >> c;
}