考研机试——其他

一 标准模板库(STL)

string

#include <string>
s.erase(10,8);  //删除s[10]开始的8个字符

在这里插入图片描述
在这里插入图片描述

二 输入输出流

#include <fstream>

void main()
{
	//读取文件
	ifstream in("D:\\123.txt");
	if (!in.is_open()) {
		cout << "error";
	}
	//文件内容输出
	while (!in.eof()) {
		char d[256];
		in.getline(d, 100);
		cout << d << endl;
	}
	
	//修改文件内容
	ofstream out("D:\\321.txt");
	for (int i = 1; i < 11; i++) {
		out << i << " ";
	}
	out.close();

	system("pause");
}

三 生产者消费者(多线程)

thread 线程 join 等待线程完成其执行
mutex 互斥锁(互斥量)
使用unique_lock 加锁解锁
unique_lock独占的是mutex对象,对mutex锁的独占

mutex mut;
unique_lock<mutex> lock(mut);  //加锁
lock.unlock();   //解锁

condition_variable 条件变量

当 std::condition_variable对象的某个wait 函数被调用的时候,它使用 std::unique_lock(通过
std::mutex) 来锁住当前线程。当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable
对象上调用了 notification 函数来唤醒当前线程。

wait 阻塞当前进程,直至被唤醒
notify_all 通知所有等待的进程

c++完成
https://blog.csdn.net/daixiangzi/article/details/80349419

#include <iostream>
#include <thread>
#include <mutex>
#include <Windows.h>
using namespace std;
#define NUM 50 //共有50个座位
struct buffer {
	int num;   //座位数量
	int front;
	int tail;
	condition_variable notEmpty;
	condition_variable notFull;
	mutex mu;
}Buffer;

typedef struct buffer buffer;

//初始化buffer
void init(buffer *b) {
	b->num = 0;
	b->front = 0;
	b->tail = 0;
}
//生产者任务
void producer() {
	for (int i = 1; i <= 10; i++) {
		//有10个客人要进入
		//第i个客人加入
		producer_task(&Buffer, i);
	}
}
//消费者任务
void consumer() {
	while (1) {
		Sleep(1);
		int i = consumer_task(&Buffer);
		//第i个客人离开
	
	}

}

void producer_task(buffer *b,int i) {  //有位置将人加入
	unique_lock<mutex> lock(b->mu);   //设置互斥锁

	while ((b->tail + 1) % NUM == b->front)  //当缓存已经满了
	{
		//无法再加入位置,只能排队
		(b->notFull).wait(lock);   //等待缓存非满
	}

	//当缓存不满时,添加人
	b->tail = (b->tail + 1) % NUM;
	++b->num;

	(b->notEmpty).notify_all();  //提醒非空
	lock.unlock();  //解锁
}
int consumer_task(buffer *b) {   //人吃完走
	unique_lock<mutex> lock(b->mu);

	while (b->front == b->tail)  //为空
	{
		//没有人,等待人进入
		b->notEmpty.wait(lock);   
	}
	//人走,空出位置
	b->front = (b->front + 1) % NUM;
	b->notFull.notify_all();  //通知有人走
	lock.unlock();

	return b->num;
}

void main()
{
	init(&Buffer);
	thread produce(producer);
	thread consume(consumer);
	produce.join();
	consume.join();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值