天天看点

C++11的多线程

C++11标准,简化了C++的多线程编程,方便了很多很多。但是,网上很多有关C++11多线程的例子,都有问题,都用了join,根本没有实现多线程的机制。现在,贴上C++11多线程的例子,通过detach实现多线程同步运行,以供参考。此例子,已在VC2012中运行过,交替输出了"func"和"func2"。

#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;

void func(){
	while(true){
		cout<<"func"<<endl;
	}
}

void func2(){
	while(true){
		cout<<"func2"<<endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	thread t1(func);
	t1.detach();
	thread t2(func2);
	t2.detach();
	system("pause");
	return 0;
}
           



继续阅读