一、同步和异步的概念
首先同步和异步是访问数据的机制
- 同步:同步一般指主动请求并等待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 非阻塞
非阻塞就是线程没有被堵住,当前线程想干啥干啥。对于非阻塞情况,用户线程读取内核空间数据,不管此时有没有数据返回给线程,当前线程都会直接返回响应结果,而不会一直在原地等待数据。