简体   繁体   English

使用 atomic bool 同步 10 个线程

[英]synchronizing 10 threads with atomic bool

I'm trying to use 10 threads and each one needs to print his number and the printing needs to be synchronized.我正在尝试使用 10 个线程,每个线程都需要打印他的号码,并且打印需要同步。 I'm doing it as homework and I have to use atomic variables to do it (no locks).我正在做作业,我必须使用原子变量来完成它(没有锁)。

Here what I tried so far:这是我到目前为止尝试过的:

#include <atomic>
#include <thread>
#include <iostream>
#include <vector>

using namespace std;
atomic<bool> turn = true;

void print(int i);

int main()
{
  vector<thread> threads;

  for (int i = 1; i <= 10; i++)
  {
    threads.push_back(thread(print, i));
  }

  for (int i = 0; i < 10; i++)
  {
    threads[i].join();
  }

  return 0;
}


void print(int i)
{
  bool f = true;
  for (int j = 0; j < 100; j++)
  {
    while((turn.compare_exchange_weak(f, false)) == false)
    { }
    cout << i << endl;
    turn = turn.exchange(true);
  }
}

output example:输出示例:

24 

9143 
541 

2 
8

expected output:预期输出:

2
4
9
1
4
3
1
5 
4
10
8

You have 2 bugs in your use of atomic .您在使用atomic有 2 个错误。

When compare_exchange_weak fails it stores the current value in the first parameter.当 compare_exchange_weak 失败时,它将当前值存储在第一个参数中。 If you want to keep trying the same value you need to set it back to the original value:如果您想继续尝试相同的值,您需要将其设置回原始值:

while ((turn.compare_exchange_weak(f, false)) == false)
{
  f = true;
}

The second issue is that exchange returns the currently stored value so:第二个问题是exchange返回当前存储的值,因此:

turn = turn.exchange(true);

Sets the value of turn back to false, you need just:将 turn back 的值设置为 false,您只需要:

turn.exchange(true);

Or even just:或者甚至只是:

turn = true;

Synchronisation isn't actually necessary in this case as std::cout will do the synchronisation for you, single output operations wont overlap so you can just change your print function to the following and it will just work:在这种情况下,实际上不需要同步,因为std::cout将为您进行同步,单个输出操作不会重叠,因此您只需将print功能更改为以下内容即可:

void print(int i)
{
    for (int j = 0; j < 100; j++)
    {
        cout << std::to_string(i) + "\n";
    }
}

Atomics aren't the right approach to this problem, your code is incredibly slow. Atomics 不是解决这个问题的正确方法,你的代码非常慢。 Mutexes would probably be quicker.互斥体可能会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM