c++多线程编程互斥锁初步
2019-08-30 11:37
22 查看
上一次讲述了多线程编程,但是由于线程是共享内存空间和资源的,这就导致:在使用多线程的时候,对于共享资源的控制要做的很好。先上程序:
#include <iostream> #include <thread> #include <chrono> #include <mutex> using namespace std; mutex mtx; void fn1() { for (int i = 0; i < 5; i++) { mtx.lock(); cout << "线程" << this_thread::get_id() << ":" << "The thread1 is running !" << endl; mtx.unlock(); } } void fn2() { for (int i = 0; i < 5; i++) { mtx.lock();//锁住的是什么资源,什么时候加锁? cout << "线程" << this_thread::get_id() << ":" << "The thread2 is running !" << endl; mtx.unlock(); } } int main() { thread t1(fn1); thread t2(fn2); t1.detach();//this_thread是否表示当前进行,而这里的当前进程是否是main函数所在进程 t2.detach(); this_thread::sleep_for(chrono::milliseconds(1000));//sleep_for表示当前进行休眠一段时间,不与其他进程竞争CPU cout << "主线程端口:" << this_thread::get_id() << endl; getchar(); return 0; }
上面一段程序,在main进程中创建了两个子线程t1,t2。对各个子线程的cout输出流进行了加锁,完了又对锁进行了释放。
其结果如下:
可见:线程t1,t2是交替执行的(这是由CPU时间片轮换造成的?)。假如我们不对cout输出流加锁,我们看看代码:
#include <iostream> #include <thread> #include <chrono> #include <mutex> using namespace std; mutex mtx; void fn1() { for (int i = 0; i < 5; i++) { //mtx.lock(); cout << "线程" << this_thread::get_id() << ":" << "The thread1 is running !" << endl; //mtx.unlock(); } } void fn2() { for (int i = 0; i < 5; i++) { //mtx.lock();//锁住的是什么资源,什么时候加锁? cout << "线程" << this_thread::get_id() << ":" << "The thread2 is running !" << endl; //mtx.unlock(); } } int main() { thread t1(fn1); thread t2(fn2); t1.detach();//this_thread是否表示当前进行,而这里的当前进程是否是main函数所在进程 t2.detach(); this_thread::sleep_for(chrono::milliseconds(1000));//sleep_for表示当前进行休眠一段时间,不与其他进程竞争CPU cout << "主线程端口:" << this_thread::get_id() << endl; getchar(); return 0; }
(就是单纯的注释掉了加锁)。
结果如下:
可以看到,结果产生了紊乱,分析一下这个结果:
线程t1才执行了一点:刚输出完“线程”两个字,转到线程2执行了,接下来再输出了线程t1的内容(并不是跑回去执行线程t1),再去执行线程t1.
造成这种紊乱的原因是:
cout本质上是一个输出流对象,相当于一个公共接口,这个接口是一个公共资源。这里就涉及到了资源共享的问题!!!
所以要对cout这个共享资源加锁!!!这样等当前的输出流执行完,才会到下一个线程!!
相关文章推荐
- C/C++_多核多线程编程_互斥锁
- 多线程编程:用互斥锁同步资源(pthread_mutex_lock测试加锁)
- C++ 多线程编程实例【2个线程模拟卖火车票的小程序】
- windows核心编程-C/C++标准库与多线程
- C++多线程编程调试技巧
- C/C++ 多线程(MultiThread)编程及几种同步方式
- Linux多线程编程之线程结合互斥锁实现同步
- C++11 多线程编程《C++ Concurrency in Action》读书笔记(3)-Sharing data between Threads
- c++ 11 多线程编程--互斥体类(1)
- 【Linux C 多线程编程】互斥锁与条件变量
- C++ 多线程编程相关
- C++简单学习(Part3_lecture 12)(多线程、Web编程)
- 多线程编程初步
- VC多线程编程初步
- 【转】Windows的多线程编程,C/C++
- Linux平台上用C++实现多线程互斥锁
- Linux平台上用C++实现多线程互斥锁
- C++ 并发编程:Mutex(互斥锁)
- C/C++多线程、线程同步(互斥锁与信号量)
- C++ 多线程编程