Created
September 3, 2017 16:56
-
-
Save e673/944842fdf477fcb0a247440a85ea7b45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <condition_variable> | |
#include <mutex> | |
#include <atomic> | |
#include <stdio.h> | |
#include <vector> | |
#include <chrono> | |
#include <Windows.h> | |
std::atomic<int> completed_count; | |
std::atomic<long long> count; | |
HANDLE oddEvent, evenEvent; | |
HANDLE completedEvent; | |
const int N = 3; | |
void wait_for_task(bool task) | |
{ | |
if (task) | |
WaitForSingleObject(oddEvent, INFINITE); | |
else | |
WaitForSingleObject(evenEvent, INFINITE); | |
} | |
void notify_task_completed() | |
{ | |
if (--completed_count == 0) | |
SetEvent(completedEvent); | |
} | |
void worker() | |
{ | |
while (true) | |
{ | |
wait_for_task(true); | |
// process task | |
notify_task_completed(); | |
wait_for_task(false); | |
// process task | |
notify_task_completed(); | |
} | |
} | |
void schedule_task(bool task) | |
{ | |
completed_count.store(N); | |
if (task) | |
{ | |
ResetEvent(evenEvent); | |
SetEvent(oddEvent); | |
} | |
else | |
{ | |
ResetEvent(oddEvent); | |
SetEvent(evenEvent); | |
} | |
} | |
void wait_for_completion() | |
{ | |
WaitForSingleObject(completedEvent, INFINITE); | |
} | |
void worker2() | |
{ | |
while (true) | |
{ | |
schedule_task(true); | |
wait_for_completion(); | |
count++; | |
schedule_task(false); | |
wait_for_completion(); | |
count++; | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
oddEvent = CreateEvent(0, true, false, 0); | |
evenEvent = CreateEvent(0, true, false, 0); | |
completedEvent = CreateEvent(0, false, false, 0); | |
std::vector<std::thread> workers; | |
std::thread thr_master(&worker2); | |
for (int i = 0; i < N; i++) | |
workers.emplace_back(&worker); | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
printf("N = %d, Count = %lld\n", N, count.load()); | |
getchar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment