#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <mutex>
#include <chrono>

using namespace std;


struct Data
{
  mutex lock;
  vector<char> v;
  char current = 'A';
  
} data;  

char next(char ch)
{
   switch(ch)	
   {
   	 case 'A': return 'B';
   	 case 'B': return 'C';
   	 case 'C': return 'A';
   }
}

void threadSafeOrderedPrint(char ch)
{
	lock_guard<mutex> l(data.lock);
	data.v.push_back(ch);
	while(!data.v.empty())
	{
	   	auto it = find(begin(data.v),end(data.v),data.current);
	   	if(it==end(data.v))
	   	  return;
	   	  
	    cout<< *it;
	    data.current = next(data.current);
	    data.v.erase(it);
	}
}


void foo(const char ch)
{
    for (int i=0; i<25; ++i) 
    {
       this_thread::sleep_for(chrono::milliseconds(10));
       threadSafeOrderedPrint(ch);
    }
}
 
int main()
{
    vector<thread> threads;
    threads.reserve(3);
    threads.emplace_back(foo, 'A');
    threads.emplace_back(foo, 'B');
    threads.emplace_back(foo, 'C');
 
    for(auto & t : threads) 
        t.join();
        
    cout<<endl<<"Finished"<<endl;    
 
    return 0;
}