Skip to content

Instantly share code, notes, and snippets.

@silahian
Created May 11, 2017 03:15
Show Gist options
  • Save silahian/168280cb535b9e906af2544ea180ca31 to your computer and use it in GitHub Desktop.
Save silahian/168280cb535b9e906af2544ea180ca31 to your computer and use it in GitHub Desktop.
busy-waiting-example created by silahian - https://repl.it/Hry2/1
#include <string>
#include <vector>
#include <thread>
#include <iostream>
#include <unistd.h>
using namespace std;
mutex mtxData;
class Consumer
{
public:
void Consume()
{
while(true)
{
mtxData.lock();
// GET DATA
// AND DO YOUR PROCESS
mtxData.unlock();
}
}
};
class Producer
{
public:
void Produce()
{
mtxData.lock();
// WRITE DATA
mtxData.unlock();
}
}
int main()
{
//launch producer thread
std::thread([&] {
Producer prod;
prod.Produce();
}
//create 5 consumers
for(int i=0; i<5; i++)
{
std::thread([&] {
Consumer cons;
cons.Consume();
}
}
//JOIN THREADS
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment