1. 面试流程
阿里云的实习面试包括4面,前三面是技术面,最后是HR面.阿里云的面试重在技术,对算法相对要求低一点,这一点跟头条是相反的,下面详细介绍典型题目.
2. 典型题目
2.1 题目介绍
c++三个线程轮流打印A,B,C.
2.2 解题思路
初次见到这个题目,首先想到的肯定是生产者消费者模型,这个是多线程题目的基本模型,一切多线程题目都是这个基本模型的变种.
接下来详细分析,本题有三个线程,要求轮流打印A,B,C.那么对于打印A的线程,只有在C已经打印完成以后,才可以执行,同理与打印B,C的线程.分析到这里我们可以想到,当前打印的最后一个字符可以对应于生产者消费者模型中的队列空,队列满.于是可以用一个变量来记录当前打印的最后一个字符.对于每一个线程,判断当前字符,如果不符合条件,就进入wait状态,符合条件的线程执行打印出字符,并signal相应的条件变量.
2.3 代码
相关的代码如下:
#include <iostream>
#include <thread>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int ready = 0;
void PrintA()
{
std::unique_lock<std::mutex> lk(mtx);
int cnt = 0;
while(cnt<10)
{
while(ready != 0)
cv.wait(lk);
std::cout<<std::this_thread::get_id()<<" : "<<"A"<<std::endl;
ready = 1;
cnt++;
cv.notify_all();
}
}
void PrintB()
{
std::unique_lock<std::mutex> lk(mtx);
int cnt = 0;
while(cnt<10)
{
while(ready != 1)
cv.wait(lk);
std::cout<<std::this_thread::get_id()<<" : "<<"B"<<std::endl;
ready = 2;
cnt++;
cv.notify_all();
}
}
void PrintC()
{
std::unique_lock<std::mutex> lk(mtx);
int cnt = 0;
while(cnt<10)
{
while(ready != 2)
cv.wait(lk);
std::cout<<std::this_thread::get_id()<<" : "<<"C"<<std::endl;
ready = 0;
cnt++;
cv.notify_all();
}
}
int main()
{
std::thread t1(PrintA);
std::thread t2(PrintB);
std::thread t3(PrintC);
t1.join();
t2.join();
t3.join();
return 0;
}
3. 后继
阿里云面试所有题目及答案见链接阿里云面试题目,预祝大家取得好的offer.