Skip to content

Instantly share code, notes, and snippets.

@alekseytimoshchenko
Created April 12, 2020 07:52
Show Gist options
  • Save alekseytimoshchenko/a796aa9b6d523342a7bc97c9845cad85 to your computer and use it in GitHub Desktop.
Save alekseytimoshchenko/a796aa9b6d523342a7bc97c9845cad85 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
std::mutex m_mtx;
std::vector<std::string> m_fileStreamer;
int getStreamInd(const std::string & fileId)
{
int ind = -1;
for (int i = 0; ind < 0 && i < m_fileStreamer.size(); i++)
ind = m_fileStreamer[i] == fileId ? i : -1;
return ind;
}
void write(const std::string & fileId)
{
if(!fileId.empty())
{
std::cout << "start " << fileId.c_str() << std::endl;
bool isIdAvailable = false;
do
{
m_mtx.lock();
isIdAvailable = getStreamInd(fileId) == -1 ;
if (!isIdAvailable)
{
m_mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
while (!isIdAvailable);
m_fileStreamer.push_back(fileId);
m_mtx.unlock();
// Sleep this thread for 200 MilliSeconds
// Some work executing
std::this_thread::sleep_for(std::chrono::milliseconds(200));
/**
* This way it doesn't works, because this line should be under `lock()` statment
* */
//int ind = getStreamInd(fileId);
m_mtx.lock();
int ind = getStreamInd(fileId); // This line should be here
m_fileStreamer.erase(m_fileStreamer.begin() + ind);
m_mtx.unlock();
std::cout << "finish " << fileId.c_str() << std::endl;
}
}
static void execution_method(std::string fileId)
{
while (true)
{
write(fileId);
}
}
int main()
{
std::thread first (execution_method, "field_id_1");
std::thread second (execution_method, "field_id_2");
first.join();
second.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment