语法问题
- const
- template
- inline
const
void f(int& n1, int& n2, const int& n3)
n1是值传递,函数内部的修改对外面没有影响。
n2是引用传递,函数内部的修改影响外面。
n3是const引用传递,函数内部不能修改。
template 函数或者类
函数模板
template< class 形参名,class 形参名,......> 返回类型 函数名(参数列表) { 函数体 }
举个例子:template <class T> void swap(T& a,T& b){}
类 模板
template< class 形参名,class 形参名,......> class 类名 {...};
举个例子:template <class T> class A { public: T a; T b; T hy(T c, T &d); };
inline 内联函数
1如果想把一个函数定义为内联函数,则需要在函数名前面放置关键字 inline,内联函数的定义必须出现在内联函数第一次调用之前。
2关键字 inline 必须与函数定义体放在一起才能使函数成为内联,仅将 inline 放在函数声明前面不起任何作用。
void func(int x, int y);
inline void func(int x, int y) { } // inline 与函数定义体放在一起
线程问题
- 线程间通信方法
- 多线程变量的权限
互斥锁mutex
某个函数需要互斥
确保了一个函数被唯一调用,有一个线程在用的时候,其它线程不能使用。
#include <iostream>
#include <thread>
#include <mutex>
class test_mutex1
{
public:
test_mutex1();
int count =0;
std::mutex mu;
void Counter()
{
std::lock_guard<std::mutex> guard(mu);
std::cout << "thread id == " << std::this_thread::get_id() << std::endl;
for(int i=0;i<5;i++)
{
count++;
std::cout << "count == " << count << std::endl;
}
}
std::thread t()
{
return std::thread([=]{Counter();});
}
void run()
{
std::thread t1=t();
std::thread t2=t();
std::thread t3=t();
std::thread t4=t();
t1.detach();
t2.detach();
t3.detach();
t4.detach();
}
};
某个变量需要互斥
mu,lock()与mu.unlock()之间的东西都会被锁起来
void Counter1()
{
std::cout << "thread id == " << std::this_thread::get_id() << std::endl;
mu.lock();
for(int i=0;i<10;i++)
{
count++;
std::cout << "count == " << count << std::endl;
}
mu.unlock();
}
void Counter2()
{
std::cout << "thread id == " << std::this_thread::get_id() << std::endl;
mu.lock();
for(int i=0;i<10;i++)
{
count--;
std::cout << "count == " << count << std::endl;
}
mu.unlock();
}
进程问题
- 创建
- 通信