Google面试题

有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推…现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:

A:1 2 3 4 1 2…

B:2 3 4 1 2 3…

C:3 4 1 2 3 4…

D:4 1 2 3 4 1…

请设计程序。
[讲解:https://www.cnblogs.com/waterfall/p/7994384.html]


#include <thread>
#include <vector>
#include <condition_variable>
#include <mutex>
#include <map>#include <semaphore.h>#define MaxThreadNums 4
#define MaxCycleNums 7namespace me {class Semaphore {public:Semaphore(long count = 0): count_(count) {}void signal() {std::unique_lock<std::mutex> lock(mutex_);++count_;cv_.notify_one();}void wait() {std::unique_lock<std::mutex> lock(mutex_);cv_.wait(lock, [=] { return count_ > 0; });--count_;}private:std::mutex mutex_;std::condition_variable cv_;long count_;};
}class File {public:File() {}void Write(char c) {std::unique_lock<std::mutex> Guard(mtx_);buffer_ += c;}std::string GetBuffer() {std::unique_lock<std::mutex> Guard(mtx_);return buffer_;}private:std::mutex mtx_;std::string name_;std::string buffer_;size_t pos_;
};/*
A:1 2 3 4 1 2....B:2 3 4 1 2 3....C:3 4 1 2 3 4....D:4 1 2 3 4 1....*/#if 10#define sem_initme::Semaphore sem_a{1};
me::Semaphore sem_b{1};
me::Semaphore sem_c{1};
me::Semaphore sem_d{1};me::Semaphore *sems[] = {&sem_a, &sem_b, &sem_c, &sem_d};#else
sem_t sem_a;
sem_t sem_b;
sem_t sem_c;
sem_t sem_d;sem_t *sems[] = {&sem_a, &sem_b, &sem_c, &sem_d};#endifint sem_wait(me::Semaphore *sem) {sem->wait();return 0;
}int sem_post(me::Semaphore *sem) {sem->signal();return 0;
}using ThreadTag = uint8_t;
using PosIdx = uint8_t ;class ThreadInfo {public:ThreadInfo(ThreadTag id) : id_(id) {}void WriteToFile(File &file) {file.Write(GetData());}uint8_t GetId() {return id_;}char GetData() {return '1' + id_;}private:ThreadTag id_;
};class WriteHelper {public:explicit WriteHelper(ThreadInfo &info) {pos_ = GetInitPosIndex(info.GetId());}File &GetFileHandler() {uint8_t idx = index_[pos_++ % MaxThreadNums];return GetFiles()[idx];}private:PosIdx index_[4] = {0, 3, 2, 1};PosIdx pos_;public:static PosIdx GetInitPosIndex(ThreadTag id) {thread_local std::map<ThreadTag, PosIdx> map_;if (map_.empty()) {// thread -> init indexmap_[0] = 0;map_[1] = 3;map_[2] = 2;map_[3] = 1;}return map_[id];}static File *GetFiles() {static File files_[MaxThreadNums];return files_;}
};// th sched: A -> B -> C -> D
void fun(ThreadInfo info) {WriteHelper helper(info);for (int i = 0; i < MaxCycleNums; i++) {sem_wait(sems[info.GetId()]);// printf("my_name: %c, %d\n", info.GetId(), info.GetData());info.WriteToFile(helper.GetFileHandler());sem_post(sems[(info.GetId() + 1) % MaxThreadNums]);}}int main() {sem_init(&sem_a, 0, 1);sem_init(&sem_b, 0, 1);sem_init(&sem_c, 0, 1);sem_init(&sem_d, 0, 1);std::thread ths[MaxThreadNums];for (int i = 0; i < MaxThreadNums; ++i) {ths[i] = std::thread(fun, ThreadInfo(i));}for (int i = 0; i < MaxThreadNums; ++i) {auto &th = ths[i];if (th.joinable()) {th.join();// printf("exit th:%d\n", i);}}for (int i = 0; i < MaxThreadNums; ++i) {auto buf = WriteHelper::GetFiles()[i].GetBuffer();printf("buf %c: %s\n", i + 'A', buf.c_str());}printf("\nmain is over\n");
}

【Google面试题】有四个线程1、2、3、4同步写入数据…C++11实现相关推荐

  1. Google面试题—有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD...

    分类: windows编程 C++ 2012-10-27 19:56 3410人阅读 评论(1) 收藏 举报 有四个线程1.2.3.4.线程1的功能就是输出1,线程2的功能就是输出2,以此类推.... ...

  2. Google面试题—有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD【转载】

    题目 有四个线程1.2.3.4.线程1的功能就是输出1,线程2的功能就是输出2,以此类推---现在有四个文件ABCD.初始都为空.现要让四个文件呈如下格式:A:1 2 3 4 1 2-.B:2 3 4 ...

  3. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】...

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  4. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  5. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】... 1

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  6. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】(修订版)...

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 什么是EL表达式? 表达式语言(Expression ...

  7. 有四个线程1、2、3、4,线程1的功能就是输出1,线程2的功能就是输出2,以此类推......... 现在有四个文件A B C D,初始都为空。现要让四个文件呈如下格式:A:1 2 3 4 1 2..

    具体题目如下: 有四个线程1.2.3.4, 线程1的功能就是输出1,线程2的功能就是输出2, 以此类推.........  现在有四个文件A B C D, 初始都为空.现要让四个文件呈如下格式: A: ...

  8. 一天十道Java面试题----第四天(线程池复用的原理------>spring事务的实现方式原理以及隔离级别)

    这里是参考B站上的大佬做的面试题笔记.大家也可以去看视频讲解!!! 文章目录 31.线程池复用的原理 32.spring是什么? 33.对Aop的理解 34.对IOC的理解 35.BeanFactor ...

  9. Google 面试题和详解

    Google的面试题在刁钻古怪方面相当出名,甚至已经有些被神化的味道.这个话题已经探讨过很多次,而科技博客 BusinessInsider这两天先是贴出15道Google面试题并一一给出了答案,其中不 ...

最新文章

  1. SpringBoot + Elasticsearch7.6实现简单查询及高亮分词查询
  2. active server pages 错误 asp 0126_最终选型 Blazor.Server:又快又稳!
  3. httpRuntime 一点经验---引
  4. docker镜像无法删除 Error:No such image:xxxxxx
  5. Mybatis Plus————代码生成器
  6. 地线与接地螺丝_电气接地的规范要求及接地的各项参数,收藏!
  7. struts2中的method
  8. RDMA over TCP的协议栈工作过程浅析
  9. cf D. Dima and Hares
  10. 基于tensorflow+RNN的MNIST数据集手写数字分类
  11. 每天一个linux命令(47):iostat命令
  12. 哈尔滨冰景:映衬时代主题
  13. 夏宇闻《Verilog数字系统设计教程》 - 第1章 Verilog的基本知识
  14. 摩尔庄园同一服务器怎么显示好友,摩尔庄园手游怎么搜索别人搜索好友步骤详解...
  15. 24位掩码和30个掩码_高级ds位掩码和dp的问题
  16. linux怎么卸载字体,Ubuntu下字体安装与卸载
  17. ***WIN2003 PHP服务器的另类技术
  18. 采用keras深度学习框架搭建卷积神经网络模型实现垃圾分类,基于树莓派上进行实时视频流的垃圾识别源代码
  19. Linear Algebra with Sub-linear Zero-Knowledge Arguments学习笔记
  20. 鸿蒙手机 OS 等开发必备工具,华为 DevEco Studio 2.1

热门文章

  1. 知足而乐,不知足亦乐
  2. groovy语法基础
  3. ubuntu安装以太方mist
  4. php怎么规范图片大小,如何在PHP中调整图片大小?
  5. 利用python实现微信自动回复群发等操作(不需要登录网页版微信)
  6. gis连接表格到数据库失败_arcgis连接到数据库失败,常规功能故障
  7. 20-50人,拓展基地_拓展训练_拓展基地_拓展公司推荐_嗨牛团建
  8. 读《爱因斯坦文集》第一卷
  9. 腹有诗书气自华——记环宇通软CEO骆永华
  10. 多伦多大学好吗_多伦多大学留学好不好