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

C++多线程编程简单体会

2017-11-05 17:29 435 查看
首先用到的是thread头文件。大概总结了三种形式。利用很著名的买票问题,其中要弄清楚多线程运行机制。以及join,detach,mutex互斥量的作用。

join:加入后,会让主进程(main函数)处于等待子线程的状态,待到子线程执行完后再回到主线程中继续执行剩下程序。(我认为这是最基本的形式,没有多线程的概念,无非是自上而下的执行)

互斥量:就是相当于锁住某个资源,防止多个线程同时修改它,或者出现一个线程正在修改,另外一个正在访问,导致出现异常的结果。切记,一旦锁住某个资源,一定要记得释放。不然其他线程在访问这个资源的时候一直会等待下去。

threadx.join();



detach:正如图上所示,主进程和子线程是互不影响的,也各做各做的。没有等待这一说。

threadx.detach();



第一种:

#include<iostream>

#include<thread> 

#include<windows.h>

using namespace std;

int total = 20;

void sellA() {

while (total > 0)
{
cout << "sellA:" << total << endl;
total--;
Sleep(100);
}

}

void sellB()

{
while (total > 0) {
cout << "sellB:" << total << endl;
total--;
Sleep(100);
}

}

int main() {
thread t1(sellA);
thread t2(sellB);
for (int i = 0; i < 5;i++)
cout << "Main is :" << i << endl;
system("pause");
return 0;

}

程序运行结果:

可以很明显的看出:上述结果有几个特点,一是main集中在一起执行;二是sellA,sellB两个窗口同时在卖一张票;

三是打印顺序比较乱(相对于main和sell来说)

加了join之后的代码:

#include<iostream>

#include<thread> 

#include<windows.h>

using namespace std;

int total = 20;

void sellA() {

while (total > 0)
{
cout << "sellA:" << total << endl;
total--;
Sleep(100);
}

}

void sellB()

{
while (total > 0) {
cout << "sellB:" << total << endl;
total--;
Sleep(100);
}

}

int main() {
thread t1(sellA);
thread t2(sellB);
t1.join();   //此处 改变
t2.join();
for (int i = 0; i < 5;i++)
cout << "Main is :" << i << endl;
system("pause");
return 0;

}

相比于第一种,这里的main和sell的顺序问题解决了,但是依旧没有解决主线程和子线程并行的问题,和重复卖同一张票的问题。

现在我们加入detach 试试

代码如下:

#include<iostream>

#include<thread> 

#include<windows.h>

using namespace std;

int total = 20;

void sellA() {

while (total > 0)
{
cout << "sellA:" << total << endl;
total--;
Sleep(100);
}

}

void sellB()

{
while (total > 0) {
cout << "sellB:" << total << endl;
total--;
Sleep(100);
}

}

int main() {
thread t1(sellA);
thread t2(sellB);
t1.detach();
t2.detach();
for (int i = 0; i < 5;i++)
{
cout << "Main is :" << i << endl;
Sleep(100);
}
system("pause");
return 0;

}

很明显main 和sell在交叉运行,这也相当于我们所说 的“并行”。但是现在依然还存在卖同一张票的问题。

下面就要用到互斥量mutex。

代码如下:

#include<iostream>

#include<thread> 

#include<windows.h>

#include<mutex>

using namespace std;

int total = 20;

mutex mu;

void sellA() {
mu.lock();
while (total > 0)
{
cout << "sellA:" << total << endl;
total--;
Sleep(100);
}
mu.unlock();

}

void sellB()

{
mu.lock();
while (total > 0) {
cout << "sellB:" << total << endl;
total--;
Sleep(100);
}
mu.unlock();

}

int main() {
thread t1(sellA);
thread t2(sellB);
t1.detach();
t2.detach();
for (int i = 0; i < 5;i++)
{
cout << "Main is :" << i << endl;
Sleep(100);
}
system("pause");
return 0;

}

上面结果就没有出现A,B两个窗口同时卖一张票的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: