同步和异步、阻塞与非阻塞

一、同步和异步的概念

首先同步和异步是访问数据的机制

  • 同步:同步一般指主动请求并等待IO操作完成的方式
  • 异步:主动请求数据后便可以继续处理其它任务,随后等待IO操作完毕的通知
    两者的区别:同步会一行一行执行代码,而异步会跳过一段接着执行后面的代码(比如回调函数就是异步的一种形式)。

二、同步与异步demo

1.同步

#include<iostream>
#include<thread>
#include<mutex>
#include<list>
#include<sstream> //拼接字符串

using namespace std;
condition_variable cond; //通知信号

static mutex mtx;
list<string> mesg;

void ReadTest(int i)
{
	for (;;)
	{
		if (mesg.empty())
		{
			this_thread::sleep_for(10ms);
			continue;
		}
		unique_lock<mutex> lock(mtx);
		cond.wait(lock);
		cout << i<<"thread recive mseg :" << mesg.front() << endl;
		mesg.pop_front();
	}
}
void WriteTest()
{
	int i = 0;
	for (;;)
	{
		this_thread::sleep_for(30ms);
		unique_lock<mutex> lock(mtx);
		stringstream ss;
		ss << "mesg" << i++;
		mesg.push_back(ss.str());
		cond.notify_one();
		cout << "send mesg" << endl;
	}

}
int main() 
{
	thread th(WriteTest);
	th.detach();
	for (int i = 0;i < 3;i++)
	{
		thread th(ReadTest,i+1);
		th.detach();
	}
	getchar();
	return 0;
}

在这里插入图片描述
发送消息后,另一接受线程收到后,发送线程才能继续发送

2.异步

#include<iostream>
using namespace std;

typedef int (*callback)(int, int);

int add(int a, int b)
{
    return a + b;

}

void fun(callback cb,int a, int b)
{
    int sum = 0;
    sum = cb(a,b);
    cout << "sum" << endl;
}

int main()
{
    callback  cb= add;
    fun(cb, 1, 2);
    return 0;
}

回调函数(callback)实现异步,代码在sum= cb(a,b);这行代码中并不会进入阻塞fun进入add函数,而是接着往下运行fun函数。

三、阻塞与非阻塞

2.1 阻塞
阻塞就是把线程堵住了,线程不能去干别的事。在阻塞情况下,用户线程读取内核空间数据,如果此时没有数据返回,那么当前线程就会被堵住,一直等到有数据返回后,当前线程才会返回响应结果。

2.2 非阻塞
非阻塞就是线程没有被堵住,当前线程想干啥干啥。对于非阻塞情况,用户线程读取内核空间数据,不管此时有没有数据返回给线程,当前线程都会直接返回响应结果,而不会一直在原地等待数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rain_ZZX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值