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

来源:互联网 发布:js动态控制div的边框 编辑:程序博客网 时间:2024/06/06 02:15

首先用到的是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两个窗口同时卖一张票的情况。