[C++ Multithreading Series] [5] Multitasking Concurrency in Different Scenarios

I'm working on a project recently, and I need to provide a set of C language interfaces for the upper layer A, and the C++ calls of the upper layer A are shared. The upper layer is concurrent. In different scenarios, the underlying interfaces are different, such as C and D. The upper C++ interface cannot directly see the different implementations of the underlying layer, but should pass in a scene id when the upper interface calls the lower interface. For B, B is responsible for calling C or D based on id. Therefore, since A supports concurrency, B cannot block. At the same time, A can guarantee that C or D can only be accessed by one thread at the same time. Since A is not assured, B locks C and D by itself. Implemented using the threading library in C++ STL.

 

[Question 1] Destruction of C++ objects

#include<iostream>
#include<thread>
using namespace std;


class A
{
public:
	A() {
		cout << "start" << endl;
	}
	~A() {
		cout << "end" << endl;
	}
};

void f(int id)
{
	if (id == 0) {
		// 在这里定义一个对象,出了{},则对象会被析构
		A a;
	}
	else {
		A a;
	}
	cout << "f end" << endl;
}

int main(int argc, int * argv[])
{

	f(0);
	system("pause");
}

The result is as follows:

It can be seen that the scope of the object is {}, and the problem is to verify that the lock_guard below can be correctly locked and unlocked.

[2] Implement the architecture of ABC/D in the above figure

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;

mutex mA;
mutex mB;

void f0()
{
	cout << "enter f0" << endl;
	for (int i = 0; i <5; i++)
	{
		cout << "i=" << i << endl;
	}
}

void f1()
{
	cout << "enter f1" << endl;
	for (int i = 20; i < 25; i++)
	{
		cout << "i=" << i << endl;
	}
}

void f(int id)
{
	if (id == 0) {
		//分场景加锁保护,防止f0被多线程访问
		std::lock_guard<mutex> _1(mA);
		f0();
	}
	else {
		//分场景加锁保护
		std::lock_guard<mutex> _1(mB);
		f1();
	}
	cout << "f end" << endl;
}

int main(int argc, int * argv[])
{

	//两个线程启动同一个函数,f内部实现场景分离
	thread t1(f, 0);
	thread t2(f, 1);
	thread t3(f, 0);
	thread t4(f, 1);
	t1.join();
	t2.join();

	t3.join();
	t4.join();
	cout << "main" << endl;
	system("pause");
}

The result is as follows:

 

It can be seen that the concurrent processing in different scenarios is successfully implemented. The reason for the disorder here is that the cout object is unique, but it is not protected by locks, resulting in multi-threaded competition for access. In fact, f0 and f1 should not have the same resources, otherwise, because f0 and f1 are not locked, it will cause resource competition. This is just to illustrate the problem, so use cout to print. The key here is the architecture and implementation of B in this scenario.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325316144&siteId=291194637