samedi 25 janvier 2020

synchronizing 10 threads with atomic bool

So i'm trying to use 10 threads and each one need to print his number and the printing need's to be synchronized. I'm doing it as home work 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);
  }
}

Aucun commentaire:

Enregistrer un commentaire