Skip to content

Instantly share code, notes, and snippets.

@haampie
Last active January 6, 2016 23:11
Show Gist options
  • Save haampie/17ce3008c6127ad05e88 to your computer and use it in GitHub Desktop.
Save haampie/17ce3008c6127ad05e88 to your computer and use it in GitHub Desktop.
locks 'n stuff
#include <condition_variable>
#include <iomanip>
#include <iostream>
#include <thread>
using namespace std;
int someNumber = 0;
mutex numberMutex;
condition_variable cv;
void waitFunction()
{
unique_lock<mutex> lock(numberMutex);
auto duration = chrono::seconds(5);
// Predicate is only called once?
cv.wait_for(lock, duration, []() {
cout << "Checking condition: 10 == " << someNumber << '\n';
return someNumber == 10;
});
cout << "Done with this thread...\n" << flush;
}
int main()
{
thread waiter(waitFunction);
for (size_t number = 0; number != 50; ++number)
{
{
lock_guard<mutex> guard(numberMutex);
someNumber = number;
}
cv.notify_one();
}
waiter.join();
}
@haampie
Copy link
Author

haampie commented Jan 6, 2016

Makefile:

CXX = g++
CXXFLAGS = -std=c++14 -pthread -Wall
LINKER = $(CXX)
LDFLAGS = -pthread

TARGET = ./bin/threads
SOURCES = main.cc $(wildcard **/*.cc)
OBJECTS = $(SOURCES:.cc=.o)

DEPS = $(OBJECTS:.o=.d)

all: $(TARGET)

$(TARGET): $(OBJECTS)
    $(LINKER) $(LDFLAGS) $(OBJECTS) $(LDLIBS) -o $@

%.o: %.cc
    $(CXX) -c $(CXXFLAGS) $(CXXINCL) $< -o $@

clean:
    rm -f $(TARGET) $(OBJECTS) $(DEPS)

-include $(DEPS)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment