首页 技术 正文
技术 2022年11月7日
0 收藏 638 点赞 433 浏览 1365 个字

代码:

  // boost库 条件变量 使用测试 #include <iostream>
#include <boost/thread.hpp>
using namespace std;boost::condition_variable cond; //关联多个线程的条件变量
boost::mutex mutex; //保护共享资源的互斥体
int k=0; //作为共享资源void func1(const int &id)
{
boost::unique_lock<boost::mutex> lock(mutex); // m->lock(); cout << "thread #hi#" << id << endl; #if 1
static int i = 0;
if(i++ == 1) // 第二个线程执行本函数,我就上锁两次,应该会锁死第二个线程自身。
boost::unique_lock<boost::mutex> lock_again(mutex); // m->lock();
#endif cout << "func1, k = " << k << endl;
while(k<5)
{
cout << "thread #" << id << " : k<5, waiting..." << endl;
cond.wait(lock);
}
cout << "thread #" << id << " : now k>5, printing..." << endl;
}
void func2(const int &id)
{
cout << "thread #hi#" << id << endl;
boost::unique_lock<boost::mutex> lock(mutex);
cout << "func2, k = " << k << endl;
cout << "thread #" << id << " : k will be changed..." << endl;
k+=5; // 模拟操作共享资源 , 在锁的保护下,此时生产者是独占性操作共享资源 cond.notify_all();//唤醒所有的等待线程
//cond.notify_one();//只会唤醒一个等待线程
}int main()
{
// 这个线程应该会顺利执行完毕
boost::thread t1(func1, 1);
boost::this_thread::sleep(boost::posix_time::seconds(1)); // 这个线程内,上锁两次,应该会锁死本线程
boost::thread t2(func1, 2); // 那么主线程还能继续向下执行吗 实测说话
// 实测能继续向下执行,
//实测,使用boost库的互斥锁和linux上的一模一样
cout << "go on" << endl;
boost::this_thread::sleep(boost::posix_time::seconds(1)); // 同理,也锁死
boost::thread t3(func2, 3); t1.join();
t2.join();
t3.join();
cout << "---end---" << endl;
return 0;
}

makefile:

.PHONY: DOITDOIT:
mips-linux-gnu-g++ -I. thread_pack.cpp -L./lib -lboost_thread -lboost_system -o boost_app

实测结论: 使用基于boost库的互斥锁、条件变量,和基于linux的原生API,效果一模一样。

.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291