【待解决问题】C++问题合集

语法问题

  • 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();
    }

进程问题

  • 创建
  • 通信
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值