线程的创建 boost_thread,boost_system
多线程的创建
线程的参数传递
线程的创建方式
线程的join
加入join,回收线程线程中断
线程中断2,
线程组
boost 线程的死锁
boost 线程递归锁
线程互斥锁,线程同步
unique_lock 锁,离开作用域自动释放
unique_lock 锁 示例 2,可以显式的释放锁
boost 1次初始化
boost 条件变量
boost 线程锁,一个账户往另外一个账户转钱案例
boost upgrade_lock

知识背景:

理解什么是线程,什么是进程,区别是什么,如何使用多进程多线程

线程的创建 boost_thread,boost_system

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;void fun()
{cout << "Hello Boost threads !" << endl;
}int main()
{boost::thread t1(fun);t1.join();return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
Hello Boost threads !
chunli@Linux:~/boost$

多线程的创建

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;void fun1(){cout << "Hello Boost threads 1!" << endl;}
void fun2(){cout << "Hello Boost threads 2!" << endl;}
void fun3(){cout << "Hello Boost threads 3!" << endl;}int main()
{boost::thread t1(fun1);    t1.join();boost::thread t2(fun2);   t2.join();boost::thread t3(fun3);   t3.join();return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
Hello Boost threads 1!
Hello Boost threads 2!
Hello Boost threads 3!
chunli@Linux:~/boost$


线程的参数传递

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
void fun1(const int &id){cout << "threads id "<<id << endl;}
void fun2(const int &id){cout << "threads id "<<id << endl;}
void fun3(const int &id){cout << "threads id "<<id << endl;}
int main()
{boost::thread t1(fun1,1);  t1.join();boost::thread t2(fun2,2); t2.join();boost::thread t3(fun3,3); t3.join();return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
threads id 2
threads id 3
chunli@Linux:~/boost$


线程的创建方式

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;void fun1(const int &id)
{cout << "threads id "<<id << endl;
}struct MyThread
{void operator()(const int &id){cout << "threads id "<<id << endl;}void fun(const int &id){cout << "threads id "<<id << endl;}
};int main()
{boost::thread t1(fun1,1);//自由函数    t1.join();MyThread mythread;    boost::thread t2(mythread,2);//函数对象   t2.join();boost::thread t3(&MyThread::fun,mythread,3); //成员函数  t3.join();boost::thread t4(MyThread(),4);  //临时对象t4.join();boost::thread t5(boost::ref(mythread),5);//对象引用 t5.join();return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
threads id 2
threads id 3
threads id 4
threads id 5
chunli@Linux:~/boost$



线程的join

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;void fun1(const int &id){cout << "threads id "<<id << endl;}int main()
{boost::thread t1(fun1,1);  //t1.join();cout << "main end!" << endl;return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!threads id 1chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!
threads id 1
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!
threads id 1chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!
threads id 1
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
main end!
threads id 1
chunli@Linux:~/boost$
可以看出,如果没有join的等待,结果是不可预期的.


加入join,回收线程

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;void fun1(const int &id){cout << "threads id "<<id << endl;}int main()
{boost::thread t1(fun1,1);  t1.join();cout << "main end!" << endl;return 0;
}
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
main end!
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
main end!
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
main end!
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
threads id 1
main end!
chunli@Linux:~/boost$

线程中断


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;void f1(const int& id)
{cout << "thread #" << id << ": started" << endl;boost::system_time const timeout = boost::get_system_time()+ boost::posix_time::seconds(3);thread::sleep(timeout);//sleep不会放弃时间片cout << "thread #" << id << ": ended" << endl;
}void f2(const int& id)
{cout << "thread #" << id << ": started" << endl;thread::yield();//预定义中断点.主动放弃时间片cout << "thread #" << id << ": ended" << endl;
}void f3(const int& id)
{cout << "thread #" << id << ": started" << endl;boost::this_thread::interruption_point();//预定义中断点cout << "thread #" << id << ": ended" << endl;
}int main()
{thread t1(f1, 1);  t1.interrupt();thread t2(f2, 2);thread t3(f3, 3);   t3.interrupt();t1.join();t2.join();t3.join();
}chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
thread #2: started
thread #1: started
thread #3: started
thread #2: ended
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
thread #1: started
thread #3: started
thread #2: started
thread #2: ended
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
thread #thread #2: started1: started
thread #3: startedthread #2: ended
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
thread #3: started
thread #1: started
thread #2: started
thread #2: ended
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
thread #2: started
thread #3: started
thread #thread #2: ended
1: started
chunli@Linux:~/boost$
只有2线程不会被打断


线程中断2,


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;void print(const int& id)
{boost::this_thread::disable_interruption di;//创建一个不可被打断的对象cout << boost::this_thread::interruption_enabled() << endl;cout << "thread #" << id << ": ";//boost::this_thread::sleep(boost::posix_time::seconds(2));boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(2);thread::sleep(timeout);for (int i = 1; i < 11; ++i){cout << i << ' ';}cout << endl;boost::this_thread::restore_interruption ri(di);//到这里,对象不可被打断cout << boost::this_thread::interruption_enabled() << endl;//实际上,是可以被打断
}int main()
{//线程还没有运行结束,叫被打断thread t1(print, 1);thread t2(print, 2);thread t3(print, 3);   t3.interrupt();t1.join();t2.join();t3.join();
}chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
0
thread #1: 0
thread #3: 0
thread #2: 1 2 3 4 5 6 7 8 9 10
1
1 2 3 4 5 6 7 8 9 10
1
1 2 3 4 5 6 7 8 9 10
1
chunli@Linux:~/boost$ g++ main.cpp -l boost_thread -l boost_system && ./a.out
0
thread #1: 0
thread #2: 0
thread #3: 1 2 3 4 5 6 7 8 9 10
1
1 2 3 4 5 6 7 8 9 10
1
1 2 3 4 5 6 7 8 9 10
1
chunli@Linux:~/boost$



线程组


chunli@Linux:~/桌面/qt_pro/01/untitled$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;
void f1(){    cout << "fun1 " << endl;}
void f2(){    cout << "fun2 " << endl;}int main()
{boost::thread_group group;for(int i = 0;i<3;++i){group.create_thread(f1);}group.add_thread(new boost::thread(f2));cout<<group.size()<<endl;group.join_all();
}chunli@Linux:~/桌面/qt_pro/01/untitled$ g++ main.cpp -lboost_thread -lboost_system -Wall && ./a.out
fun1 4
fun1
fun2
fun1 chunli@Linux:~/桌面/qt_pro/01/untitled$ g++ main.cpp -lboost_thread -lboost_system -Wall && ./a.out
fun1
fun1
fun1
4
fun2
chunli@Linux:~/桌面/qt_pro/01/untitled$


boost 线程的死锁


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;boost::mutex m;void function1()
{m.lock();cout << "function 1 \n";m.unlock();
}void function2()
{m.lock();cout << "function 2 \n";function1();m.unlock();
}int main()
{thread t1(function1);   t1.join();thread t2(function2);   t2.join();
}chunli@Linux:~/boost$ g++ main.cpp -lboost_thread -lboost_system&& ./a.out
function 1
function 2
^C
chunli@Linux:~/boost$



boost 线程递归锁


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;boost::recursive_mutex m;void function1()
{m.lock();cout << "function 1 \n";m.unlock();
}void function2()
{m.lock();cout << "function 2 \n";function1();m.unlock();
}int main()
{thread t1(function1);   t1.join();thread t2(function2);   t2.join();
}chunli@Linux:~/boost$ g++ main.cpp -lboost_thread -lboost_system -lpthread && ./a.out
function 1
function 2
function 1
chunli@Linux:~/boost$


线程互斥锁,线程同步

boost::mutex m;void function1(int id)
{m.lock();cout <<"thread #"<<id<<":";for(int i=0;i<15;i++)cout << i<<' ';cout << endl;m.unlock();
}int main()
{thread t1(function1,1);   t1.join();thread t2(function1,2);   t2.join();thread t3(function1,3);   t3.join();thread t4(function1,4);   t4.join();thread t5(function1,5);   t5.join();thread t6(function1,6);   t6.join();}chunli@Linux:~/boost$ g++ main.cpp -lboost_thread -lboost_system -lpthread && ./a.out
thread #1:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
thread #2:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
thread #3:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
thread #4:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
thread #5:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
thread #6:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
chunli@Linux:~/boost$


unique_lock 锁,离开作用域自动释放


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <list>#include <boost/thread.hpp>
using namespace std;
using boost::thread;boost::mutex m;
int k = 0;void decrement()
{boost::unique_lock<boost::mutex> lock(m);for(int i = 0;i<=100;++i){k-=i;}cout << "after decrement k="<<k << endl;
}void increment()
{boost::unique_lock<boost::mutex> lock(m);for(int i = 0;i<=100;++i){k+=i;}cout << "after increment k="<<k << endl;
}int main()
{boost::thread t1(increment);    t1.join();boost::thread t2(decrement);    t2.join();}chunli@Linux:~/boost$ g++ main.cpp -lboost_thread -lboost_system -lpthread && ./a.out
after increment k=5050
after decrement k=0
chunli@Linux:~/boost$


unique_lock 锁 示例 2,可以显式的释放锁

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <vector>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;boost::mutex m;void updateString()
{boost::unique_lock<boost::mutex> lock(m);//locklock.unlock();//unlocklock.lock();
}int main()
{thread t1(updateString);    t1.join();thread t2(updateString);    t2.join();
}chunli@Linux:~/boost$ g++ main.cpp -lboost_thread -lboost_system -lpthread && ./a.out
chunli@Linux:~/boost$



boost 1次初始化

chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>using namespace std;
using boost::thread;
boost::once_flag once = BOOST_ONCE_INIT; // 注意这个操作不要遗漏了
void func() {cout << "Will be called but one time!" << endl;
}
void threadFunc() {//    func();boost::call_once(&func, once);
}int main() {boost::thread_group threads;for (int i = 0; i < 5; ++i)threads.create_thread(&threadFunc);threads.join_all();
}chunli@Linux:~/boost$ g++ main.cpp  -lboost_thread -lboost_system && ./a.out
Will be called but one time!
chunli@Linux:~/boost$



boost 条件变量


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using boost::thread;boost::condition_variable cond; // 关联多个线程的条件变量
boost::mutex m; // 保护共享资源 k 的互斥体
int k = 0; // 共享资源void f1(const int& id)
{boost::unique_lock<boost::mutex> lock(m);while (k < 5) {cout << "thread #" << id << ": k < 5, waiting ..." << endl;cond.wait(lock); // #1}cout << "thread #" << id << ": now k >= 5, printing ..." << endl;
}void f2(const int& id)
{boost::unique_lock<boost::mutex> lock(m);cout << "thread #" << id << ": k will be changed ..." << endl;k += 5;cond.notify_all(); // #2 不需lock
}int main() {// 如果f2()中是 cond.notify_one(),结果?boost::thread t1(f1, 1);boost::thread t2(f1, 2);boost::thread t3(f2, 100);t1.join();t2.join();t3.join();
}chunli@Linux:~/boost$ g++ main.cpp  -lboost_thread -lboost_system && ./a.out
thread #1: k < 5, waiting ...
thread #2: k < 5, waiting ...
thread #100: k will be changed ...
thread #1: now k >= 5, printing ...
thread #2: now k >= 5, printing ...
chunli@Linux:~/boost$


boost 线程锁,一个账户往另外一个账户转钱案例


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>using namespace std;
using boost::thread;class Account {boost::mutex m;double balance;public:Account() :balance() {}Account(const double& bal) :balance(bal) {}double getBalance() const {return balance;}friend void transfer(Account& from, Account& to, double amount);
};version 3: OK (使用lock() 和 unique_lock)
//void transfer(Account& from, Account& to, double amount) {
//    boost::lock(from.m, to.m);
//    boost::unique_lock<boost::mutex> lockFrom(from.m, boost::adopt_lock);
//    boost::unique_lock<boost::mutex> lockTo(to.m, boost::adopt_lock);
//
//    from.balance -= amount;
//    to.balance += amount;
//}// version 2: OK (使用lock() 和 lock_guard)
void transfer(Account& from, Account& to, double amount) {boost::lock(from.m, to.m);boost::lock_guard<boost::mutex> lockFrom(from.m, boost::adopt_lock);boost::this_thread::sleep(boost::posix_time::seconds(1));boost::lock_guard<boost::mutex> lockTo(to.m, boost::adopt_lock);from.balance -= amount;to.balance += amount;
}// version 1: 可能造成死锁
//void transfer(Account& from, Account& to, double amount) {
//    boost::lock_guard<boost::mutex> lockFrom(from.m); // #1
//    boost::this_thread::sleep(boost::posix_time::seconds(1));
//    boost::lock_guard<boost::mutex> lockTo(to.m); // #2
//    from.balance -= amount;
//    to.balance += amount;
//}int main() {Account a1(1200.00);Account a2(300.00);boost::thread t1(transfer, boost::ref(a1), boost::ref(a2), 134.85);boost::thread t2(transfer, boost::ref(a2), boost::ref(a1), 100.30);t1.join();t2.join();cout << "Balance of a1: " << a1.getBalance() << endl;cout << "Balance of a2: " << a2.getBalance() << endl;
}chunli@Linux:~/boost$ g++ main.cpp  -lboost_thread -lboost_system -lpthread && ./a.out
Balance of a1: 1165.45
Balance of a2: 334.55
chunli@Linux:~/boost$



boost upgrade_lock


chunli@Linux:~/boost$ cat main.cpp
#include <iostream>
#include <boost/thread.hpp>using namespace std;
using boost::thread;
boost::shared_mutex m;
int k = 1;void f(int id) {boost::upgrade_lock<boost::shared_mutex> lock(m);cout << "thread #" << id << ": " << k << endl;if (k < 6) {// boost::unique_lock<boost::shared_mutex> lock2(boost::move(lock)); // alternate:boost::upgrade_to_unique_lock<boost::shared_mutex> lock2(lock);k += 3;}
}int main() {boost::thread t1(f, 1);boost::thread t2(f, 2);boost::thread t3(f, 3);t1.join();t2.join();t3.join();
}chunli@Linux:~/boost$ g++ main.cpp  -lboost_thread -lboost_system -lpthread && ./a.out
thread #2: 1
thread #1: 4
thread #3: 7
chunli@Linux:~/boost$

转载于:https://blog.51cto.com/990487026/1886403

9 C++ Boost 多线程,线程同步相关推荐

  1. java同步与死锁_Java多线程 - 线程同步与死锁

    一.线程同步 1)模拟多个用户同时从银行账户里面取钱 ● Account 类:银行账户类,里面有一些账户的基本信息,以及操作账户信息的方法 //模拟银行账户 classAccount {private ...

  2. 第18章 多线程----线程同步

    Java提供了线程同步的机制来防止资源访问的冲突. 1.线程安全 实际开发中,使用多线程程序的情况很多,如银行排号系统.火车站售票系统等.这种多线程的程序通常会发生问题. 以火车站售票系统为例,在代码 ...

  3. C#中的多线程-线程同步基础 (控制线程数量)

    同步要领 下面的表格列展了.NET对协调或同步线程动作的可用的工具: 简易阻止方法 构成 目的 Sleep 阻止给定的时间周期 Join 等待另一个线程完成 锁系统 构成 目的 跨进程? 速度 loc ...

  4. Python多线程——线程同步

    创建多线程 继承Thread类创建派生类,并重写__init__和run方法,实现自定义线程对象类: import threading import timeclass myThread(thread ...

  5. Java 多线程 线程同步

    线程同步 1.发生在多个线程操作同一个资源 2.并发:同一个对象被多个线程同时操作 3.于是,就需要线程同步.线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等 ...

  6. 13-多线程01 实现多线程 线程同步 生产者消费者

    1.实现多线程 1.1简单了解多线程[理解] 是指从软件或者硬件上实现多个线程并发执行的技术. 具有多线程能力的计算机因有硬件支持而能够在同一时间执行多个线程,提升性能. 1.2并发和并行[理解] 并 ...

  7. java例程练习(多线程[线程同步问题])

    //线程同步问题 public class TestThread implements Runnable{Timer timer = new Timer();public static void ma ...

  8. 多线程 - 线程同步

    线程同步 线程同步机制 点击链接跳转大佬网址 同步方法及同步块 同步方法 //模拟买票 public class TestDemo03 {public static void main(String[ ...

  9. Linux多线程 | 线程同步

    文章目录 前言 主要介绍四种常用的线程同步方式以及相关的函数接口. 一.线程同步 二.同步方法 1.互斥锁 2.信号量 3.条件变量 4.读写锁 总结 前言 主要介绍四种常用的线程同步方式以及相关的函 ...

最新文章

  1. 一个插排引发的设计思想 (一) 观察者模式
  2. [1025]Noip 2009 Problem 2
  3. 刷magisk模块后不能开机_联想启天商用电脑刷BIOS或维修换主板后 开机叫两声处理办法...
  4. 用于软件包管理的21个Linux YUM命令
  5. springboot忽略证书_SpringBoot获取resource下证书失败
  6. webservice系列1---基于web工程上写一个基本数据类型的webservice
  7. matlab自适应遗传算法代码,自适应遗传算法MATLAB代码
  8. 单片机c语言仿真,单片机c语言教程:C51表达式语句及仿真器
  9. 物联网工程导论第二版答案选择题
  10. 使用C#实现DHT磁力搜索的BT种子后端管理程序+数据库设计(开源)[搜片神器]
  11. 学习python自动化测试的好处
  12. java登陆注册界面_java编写登陆注册页面(简单一点的,连接数据库)
  13. 如何隐藏logo 高德地图api_高德地图api 去掉logo
  14. java计算机毕业设计html5健身房信息管理系统源码+数据库+系统+lw文档
  15. 统计考勤报表 oracle对多个列求和 sum() 函数
  16. MES系统多少钱?企业需要什么样的MES系统?
  17. CSS 笔记——定位尺寸
  18. Ubuntu使用sudo apt-get upgrade升级软件出现问题后的处理
  19. 深度linux桌面卸载wps,安装,卸载WPS-office报错,如何解决?
  20. 通达信交易系统测试软件,{通达信高级智能交易系统}正确的公式

热门文章

  1. 走进javascript——不起眼的基础,值和分号
  2. [一个经典的多线程同步问题]解决方案一:关键段CS
  3. 如何加强测评机构自身的规范化管理, 不断提高测评的能力和水平
  4. 分析android动画模块[转]
  5. 使silverlight适应IE窗口大小的方法
  6. request获取mac地址_【Go】获取用户真实的ip地址
  7. iView 实战系列教程(21课时)_2.iView 实战教程之导航、路由、鉴权篇
  8. labelme2coco问题:TypeError: Object of type 'int64' is not JSON serializable
  9. C#将unix时间戳转换成.net的DateTime类型的代码
  10. Confluence 6 配置服务器基础地址备注