标签:style blog http color os io ar for 2014
1.多线程
多线程案例:
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
using namespace std;
void run(int num)
{
Sleep(1000);
std::cout << "你好天朝" << num << endl;
}
void main()
{
thread *p[10];
for (int i = 0; i < 10;i++)
{
p[i] = new thread(run,i);//循环创建线程
//p[i]->join();//等待,相当于堵塞的状态
p[i]->detach();//脱离当前主线程自由执行,乱序,也就是说每个线程的执行是随机的,是并发执行。
}
cin.get();
}
运行结果是:
2.线程案例2
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
using namespace std;
void helloworld()
{
std::cout << "你好天朝" << endl;
}
void helloworldA()
{
std::cout << "你好天朝A" << endl;
}
void helloworldB()
{
std::cout << "你好天朝B" << endl;
}
//通过下面这种方式实现的线程永远是顺序的
void main()
{
std::thread t1(helloworld);//线程顺序执行
std::thread t2(helloworldA);
std::thread t3(helloworldB);
cin.get();
}
3.线程加锁和线程解锁
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
#include<mutex>
using namespace std;
//两个线程并行访问一个变量
int g_num = 20;//找到或者找不到的标识
mutex g_mutex;
void goA(int num)
{
//你访问的变量,在你访问期间,别人访问不了,
//这种情况明显可以看到自己被执行的次数多了
g_mutex.lock();
for (int i = 0; i < 15; i++)
{
Sleep(300);
g_num = 10;
std::cout << "线程" << num << " " << g_num << endl;
}
g_mutex.unlock();
}
void goB(int num)
{
for (int i = 0; i < 15; i++)
{
Sleep(500);
g_num = 11;
std::cout << "线程" << num << " " << g_num << endl;
}
}
void main()
{
thread t1(goA,1);
thread t2(goB, 2);
t1.join();
t2.join();
std::cin.get();
}
运行结果:
4.线程之间通信以及锁定
案例:
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
using namespace std;
//两个线程并行访问一个变量
//找到或者找不到的标识
int g_num = 20;
void goA(int num)
{
for (int i = 0; i < 15;i++)
{
Sleep(1000);
if (i == 6)
{
g_num = 5;
}
if (g_num == 5)
{
std::cout << "线程" << num << "结束\n";
return;
}
std::cout << "线程" << num << " " << g_num << endl;
}
}
void goB(int num)
{
for (int i = 0; i < 150; i++)
{
Sleep(1000);
if (g_num == 5)
{
std::cout << "线程" << num << "结束 \n";
return;
}
std::cout << "线程" << num << " " << g_num << endl;
}
}
void main()
{
thread t1(goA, 1);
thread t2(goB, 2);
t1.join();
t2.join();
std::cin.get();
}
标签:style blog http color os io ar for 2014
原文地址:http://blog.csdn.net/tototuzuoquan/article/details/38948601