您的位置:首页 > 编程语言 > C语言/C++

C++多线程

2015-12-09 19:26 405 查看


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();

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: