C++ multithreading learning (twelve, special atomic type atomic_flag, spin lock)

Table of contents

atomic_flag

spin lock

The difference between spin lock and mutex

 1. The waiting method is different:

2. Different resource consumption:

3. The applicable scenarios are different:

simple case


Other atomic types can use is_lock_free() to determine whether they are lock-free

atomic_flag

atomic_flag: is lock-free

atomic_flag contains two functions inside:

1.test_and_set(): If it is not set, it is set, if it is set, it returns true.

2.clear(): Clear the mark, so that the next call to test_and_set() returns false.

spin lock

The difference between spin lock and mutex

In the same example, the mutex is A going to the toilet, B waiting at the door.

The spin lock means that A is going to the toilet, and B is still doing his own thing, until A comes out after going to the toilet, and B goes directly to it.

 1. The waiting method is different:


        Spin lock : When a thread requests a spin lock, if the lock is already occupied by other threads, the requesting thread will spin and wait in a busy-wait manner, that is, repeatedly check whether the lock is available until the lock is acquired.
        Mutex lock : When a thread requests a mutex lock, if the lock is already occupied by other threads, the requesting thread will enter a blocked state, and will not be awakened to continue execution until the lock is acquired.



2. Different resource consumption:


        Spin lock : During the spin waiting period, the requesting thread will always occupy CPU resources. If the spin waiting time is too long, CPU resources will be wasted.
        Mutual exclusion lock : During the blocking waiting period, the requesting thread does not occupy CPU resources, and the thread competes for the lock after being awakened.



3. The applicable scenarios are different:


        Spin lock : It is suitable for situations where the protection critical section is small and the lock competition is very short, because the spin wait consumes CPU resources.
        Mutual exclusion lock : It is suitable for situations where the protection critical section is large and the lock competition is fierce, because blocking waiting does not occupy CPU resources.

simple case

#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
//初始化:也可以用atomic_flag lock = {};
atomic_flag lock = ATOMIC_FLAG_INIT;//ATOMIC_FLAG_INIT这个宏定义是大括号:{}

void test1(int n)
{
	while (lock.test_and_set())//可以不传参,有重载的枚举类型【之前讲过】
	{
		printf("等待中...%d\n", n);
	}
	printf("线程完成...%d\n", n);
}
void test2(int n)
{
	printf("线程启动:%d\n",n);
	this_thread::sleep_for(1s);
	lock.clear();
	printf("线程运行结束:%d\n", n);
}
int main()
{
	lock.test_and_set();
	thread t1(test1, 1);
	thread t2(test2, 2);
	t1.join();
	t2.join();


	return 0;
}

Guess you like

Origin blog.csdn.net/q244645787/article/details/131614188