Skip to content

Instantly share code, notes, and snippets.

@nihui
Last active July 3, 2019 15:52
Show Gist options
  • Save nihui/24e901118ab54426a3da65042530f43c to your computer and use it in GitHub Desktop.
Save nihui/24e901118ab54426a3da65042530f43c to your computer and use it in GitHub Desktop.
load proc save
using namespace ncnn;
class TaskQueue
{
public:
TaskQueue()
{
}
void put(int v)
{
lock.lock();
while (tasks.size() >= 10)
{
condition.wait(lock);
}
tasks.push(v);
lock.unlock();
condition.signal();
}
void get(int& v)
{
lock.lock();
while (tasks.size() == 0)
{
condition.wait(lock);
}
v = tasks.front();
tasks.pop();
lock.unlock();
condition.signal();
}
private:
Mutex lock;
ConditionVariable condition;
std::queue<int> tasks;
};
TaskQueue toproc;
TaskQueue tosave;
void* load(void*)
{
#pragma omp parallel for num_threads(2)
for (int i = 0; i < 100; i++)
{
int v;
Sleep((rand() % 10));
v = i;
fprintf(stderr, "load %d\n", v);
toproc.put(v);
}
fprintf(stderr, "load done!\n");
return 0;
}
void* proc(void*)
{
for (;;)
{
int v;
toproc.get(v);
if (v == -233)
break;
fprintf(stderr, " proc %d\n", v);
Sleep((rand() % 10));
v = v + 100;
fprintf(stderr, " proc %d done\n", v);
tosave.put(v);
}
fprintf(stderr, "proc done!\n");
return 0;
}
void* save(void*)
{
for (;;)
{
int v;
tosave.get(v);
if (v == -233)
break;
fprintf(stderr, " save %d\n", v);
Sleep((rand() % 10));
}
fprintf(stderr, "save done!\n");
return 0;
}
int main(int argc, char** argv)
{
// load image
Thread t1(load);
// waifu2x
Thread t2(proc);
Thread t22(proc);
// save image
Thread t3(save);
Thread t33(save);
t1.join();
toproc.put(-233);
toproc.put(-233);
t2.join();
t22.join();
tosave.put(-233);
tosave.put(-233);
t3.join();
t33.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment