Skip to content

Instantly share code, notes, and snippets.

@igricart
Created August 12, 2020 18:06
Show Gist options
  • Select an option

  • Save igricart/ba060873431ed865c55eca51d8bf943e to your computer and use it in GitHub Desktop.

Select an option

Save igricart/ba060873431ed865c55eca51d8bf943e to your computer and use it in GitHub Desktop.
Multithreading
#include <assert.h>
#include <thread>
#include <mutex>
#include <future>
#include <iostream>
#include <deque>
int a = 0;
std::mutex mutex;
void increment()
{
while (true)
{
mutex.lock();
int prev = a;
a++;
assert((prev + 1) == a);
mutex.unlock();
}
}
int main2()
{
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
return 0;
}
int value = 0;
bool value_ready = false;
void LongOperation()
{
std::cout << "long operation started" << std::endl;
{
std::unique_lock<std::mutex> lock_A(mutex);
// std::this_thread::sleep_for(std::chrono::seconds(1));
// value = 42;
// value_ready = true;
std::cout << "long operation done" << std::endl;
}
}
std::condition_variable cv;
std::deque<int> queue;
void Producer()
{
for (int i = 0; i < 10; i++)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::unique_lock<std::mutex> lock(mutex);
queue.push_back(i);
std::cout << "pushed: " << i << std::endl;
}
cv.notify_all();
std::this_thread::sleep_for(std::chrono::microseconds(10));
cv.notify_all();
}
}
void Consumer()
{
while (true)
{
int value = -1;
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, []() { std::cout << "attempt" <<std::endl; return !queue.empty(); });
value = queue.front();
queue.pop_front();
}
std::cout << "received: " << value << std::endl;
}
}
int main()
{
std::thread t1(Producer);
std::thread t2(Consumer);
t1.join();
t2.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment