C++11笔记

在使用uWebSocket的时候 用到了大量的c++11 特性,在次稍微做下笔记:
1.std::aray
除了有传统数组支持随机访问、效率高、存储大小固定等特点外,还支持迭代器访问、获取容量、获得原始指针等高级功能。而且它还不会退化成指针T *给开发人员造成困惑。
例:
std::array<int, 10> arr = {1,2,3,4,5,6,7,8,9,0};
std::for_each(arr.begin(), arr.end(), [](int &i){i++;});
for(auto i : arr){std::cout << i << " ";}

std::for_each 和 for(auto i : arr) 也是一个特色,平时很少这样用,可能是我比较守旧。

2.std::thread
构造函数的例子:
#include < thread>
#include < chrono>
using namespace std;
void fun1(int n) //初始化构造函数
{
cout << “Thread " << n << " executing\n”;
n += 10;
this_thread::sleep_for(chrono::milliseconds(10));
}
void fun2(int & n) //拷贝构造函数
{
cout << “Thread " << n << " executing\n”;
n += 20;
this_thread::sleep_for(chrono::milliseconds(10));
}
int main()
{
int n = 0;
thread t1; //t1不是一个thread
thread t2(fun1, n + 1); //按照值传递
t2.join();
cout << “n=” << n << ‘\n’;
n = 10;
thread t3(fun2, ref(n)); //引用
thread t4(move(t3)); //t4执行t3,t3不是thread
t4.join();
cout << “n=” << n << ‘\n’;
return 0;
}

特色:
fun1,fun2的区别
this_thread::sleep_for 的使用
chrono::milliseconds(10)
ref(n)
std::ref可以在模板传参的时候传入引用,否则无法传递,std::ref只是尝试模拟引用传递,并不能真正变成引用,在非模板情况下,std::ref根本没法实现引用传递,只有模板自动推导类型时,ref能用包装类型reference_wrapper来代替原本会被识别的值类型,而reference_wrapper能隐式转换为被引用的值的引用类型。

join(); 不调用join结束的时候会报错。
hread (thread&& x)
move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。
thread (const thread&) = delete;
(被禁用),意味着 thread 不可被拷贝构造。

线程函数可以任意传,多个都可以;

join 是让当前主线程等待所有的子线程执行完,才能退出。
detach 脱离主线程的绑定,主线程挂了,子线程不报错,子线程执行完自动退出。

thread::hardware_concurrency();//获取cpu核心个数

复习一下time.h clock 的使用:
long i = 10000000L;
clock_t start = clock();
while( i-- ) ;
clock_t finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;

CLOCKS_PER_SEC:每秒钟跳多少次
#define CLOCKS_PER_SEC ((clock_t)1000) 即每秒钟跳1000次(毫秒),运行时间为 duration 秒。

复习一下互斥量:
#include< mutex>
mutex m;
m.lock();
//同步内容
m.unlock();
亲测发现使用时间特别长64s。原因是大量的加解锁。

原子变量:
#include
atomic_int num{ 0 };

使用原子变量时间明显比互斥量快3到4倍18s。

通过jion等待
thread t1(run);
1.join();
thread t2(run);
t2.join();

时间540ms,非常快,但这样就是相当于单线程,即如果有共享东西多线程就会比单线程慢好多,因为要处理同步的东西。

可变参数函数的参数列表:

va_list ap;//指针
va_start(ap, fun);//开始
va_arg(vaList,char*)
// vprintf(fun, ap);//调用
//vsprintf
//vsnprintf
va_end(ap);

参考文章:https://www.cnblogs.com/lidabo/p/7852033.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值