使用CAS实现:
//实现三个线程分别打印1,2,3...
std::atomic<int> counter(1);
std::atomic<int> one(1);
std::atomic<int> two(2);
std::atomic<int> three(3);
void print_one() //最后打印的值是100
{
while (true)
{
if (one.load(std::memory_order_acquire)==103) //打印100后,one的值为103,此时退出
return;
int old_value = counter.load(std::memory_order_acquire);
while (!one.compare_exchange_weak(old_value, old_value + 3))
{
old_value = counter.load(std::memory_order_acquire);
}
std::cout << "thread__one : " << old_value << std::endl;
counter += 1;
}
}
void print_two() //最后打印的值是98
{
while (true)
{
if (two.load(std::memory_order_acquire) ==101)//打印100后,one的值为101,此时退出
return;
int old_value = counter.load(std::memory_order_acquire);
while (!two.compare_exchange_weak(old_value, old_value + 3))
{
old_value = counter.load(std::memory_order_acquire);
}
std::cout << "thread__two : " << old_value << std::endl;
counter += 1;
}
}
void print_three() //最后打印的值是99
{
while (true)
{
if (three.load(std::memory_order_acquire) == 102) //打印100后,one的值为102,此时退出
return;
int old_value = counter.load(std::memory_order_acquire);
while (!three.compare_exchange_weak(old_value, old_value + 3))
{
old_value = counter.load(std::memory_order_acquire);
}
std::cout << "thread__three: " << old_value << std::endl;
counter += 1;
}
}
int main()
{
std::thread t_one(print_one);
std::thread t_two(print_two);
std::thread t_three(print_three);
t_one.join();
t_two.join();
t_three.join();
}
CAS实现,结合线程局部变量:
std::atomic<int> count{1};
thread_local int c;
void thread_one() //最后打印的值是199
{
c = 1;
while (true)
{
if (c > 199)
return;
if (count.load() == c)
{
std::cout << "打印1的线程:" << c << std::endl;
c += 3;
count++;
}
}
}
void thread_two() //最后打印的值是200
{
c = 2;
while (true)
{
if (c > 200)
return;
if (count.load() == c)
{
std::cout << "打印2的线程:" << c << std::endl;
c += 3;
count++;
}
}
}
void thread_three() //最后打印的值是198
{
c = 3;
while(true)
{
if (c > 198)
return;
if (count.load() == c)
{
std::cout << "打印3的线程:" << c << std::endl;
c += 3;
count++;
}
}
}
int main()
{
std::thread t1(thread_one), t2(thread_two), t3(thread_three);
t1.join();
t2.join();
t3.join();
}
使用互斥量mutex实现:
std::mutex mt;
int count_mt = 1;
void thread_one()
{
while (true)
{
std::lock_guard<std::mutex> lock(mt);
if (count_mt > 100)
return;
if (count_mt % 3 == 1)
std::cout << "thread_one: " << count_mt++ << std::endl;
}
}
void thread_two()
{
while (true)
{
std::lock_guard<std::mutex> lock(mt);
if (count_mt > 100)
return;
if (count_mt % 3 == 2)
std::cout << "thread_two: " << count_mt++ << std::endl;
}
}
void thread_three()
{
while (true)
{
std::lock_guard<std::mutex> lock(mt);
if (count_mt > 100)
return;
if (count_mt % 3 == 0)
std::cout << "thread_three: " << count_mt++ << std::endl;
}
}
int main()
{
std::vector<std::thread> vec;
vec.emplace_back(std::thread(thread_one));
vec.emplace_back(std::thread(thread_two));
vec.emplace_back(std::thread(thread_three));
for (auto& v : vec)
v.join();
}