Effective Modern C++:constexpr, thread safe

constexpr is more strict than const

int a;
const b = a;//correct
constexpr c = a;//wrong, because a has no value yet

When declaring a constexpr, it should be assigned with a already existed value.

you can get compile-time result when using constexpr function

constexprfunc

Amazing, no debugging needed, when you are codding, you already know the result.

Thread safe programming

Use lock_guard to keep the whole function thread safe:

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

class busy
{
public:
	void compute(int a)
	{
		lock_guard<mutex> guard(m);//keep safe here
		cout << a <<" "<< curr << endl;
		curr += 1.0;
	}
private:
    double curr = 3.0;
	mutable mutex m;
};

busy bus;

void thread1()
{
	for (int i = 0; i < 10; i++)
		bus.compute(1);
}
void thread2()
{
	for (int i = 0; i < 10; i++)
		bus.compute(2);
}
void main()
{
	thread t1(thread1);
	thread2();
	t1.join();
}

The mutex and lock_guard is used to keep the thread save.

If we don’t use mutex and lock_guard, everything will get crazy:

1 3
2 3
1 4
1 5
2 6
2 8
2 1 7
9
2 11
1 10
2 12
1 13
1 2 14
15
2 1 16
17
2 1 19
18
1 20
2 21

Using mutex and lock_guard, the output is like this:

1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
1 11
1 12
2 13
2 14
2 15
2 16
2 17
2 18
2 19
2 20
2 21
2 22

Use atomic to keep a single variable thread safe:

mutable std::atomic<int> callCount{ 0 };

Just wrap the variable as above, it becomes thread safe.

Wangxin -->

Wangxin

I am algorithm engineer focused in computer vision, I know it will be more elegant to shut up and show my code, but I simply can't stop myself learning and explaining new things ...