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

一、同步和异步的概念

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

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

二、同步与异步demo

1.同步

#include
#include
#include
#include
#include //拼接字符串

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;
}

同步和异步、阻塞与非阻塞_第1张图片
发送消息后,另一接受线程收到后,发送线程才能继续发送

2.异步

#include
#include
#include 
using namespace std;

typedef void(*CB)();

void callback()
{
    cout << "Cb" << endl;
    for (int i = 0; i < 10; i++)
    {
        cout << i + 1 << endl;
        this_thread::sleep_for(200ms);
    }
}

void CbTest(CB cb)
{
    cout << "CbTest" << endl;
    // 创建异步任务来执行回调函数
    std::future<void> fut = std::async(std::launch::async, cb);

    // 主线程继续执行其他操作
    cout << "Main thread continues" << endl;
    cout << "test" << endl;
    // 等待异步任务完成
    fut.get();
}

int main()
{
    CB cb = callback;
    CbTest(cb);
    return 0;
}

同步和异步、阻塞与非阻塞_第2张图片
在执行循环的同时 也执行了打印test这行代码

三、阻塞与非阻塞

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

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

你可能感兴趣的:(学习,c++)