aboutsummaryrefslogtreecommitdiff
path: root/NvCloth/samples/SampleBase/utils/JobManager.h
blob: 648fa336421d157a993ce6df2d02e25c1e0c98be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
* Copyright (c) 2008-2017, NVIDIA CORPORATION.  All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto.  Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/

#pragma once

#include <foundation/PxErrorCallback.h>
#include <regex>
#include "CallbackImplementations.h"
#include <mutex>
#include <thread> 
#include <condition_variable>

#include <foundation/PxVec4.h>
#include <foundation/PxVec3.h>
#include <vector>
#include <queue>
#include <atomic>

#include <task/PxTaskManager.h>
#include <task/PxTask.h>

namespace nv
{
namespace cloth
{
class Solver;
}
}

///Dummy task that can be used as end node in a task graph.
class DummyTask : public physx::PxTask
{
public:
	DummyTask() { mFinished = false; mTm = nullptr; }
	DummyTask(physx::PxTaskManager* tm) { mFinished = false; mTm = tm; mTm->submitUnnamedTask(*this); }
	~DummyTask() { mTm = nullptr; } //Way to catch race conditions. Will usually crash on nullptr if the task gets deleted before the taskmanager is done with it.
	
	virtual void run() override { }
	virtual void release() override { physx::PxTask::release(); mFinished = true; mWaitEvent.notify_all(); }
	virtual const char* getName() const override { return "DummyTask"; }

	void Reset(physx::PxTaskManager* tm) { mFinished = false; mTm = tm; mTm->submitUnnamedTask(*this); }

	///Use Wait to block the calling thread until this task is finished and save to delete
	void Wait()
	{
		std::mutex eventLock;
		std::unique_lock<std::mutex> lock(eventLock);
		while (!mFinished) { mWaitEvent.wait(lock); }
	}

private:
	std::condition_variable mWaitEvent;
	bool mFinished;
};

class CpuDispatcher : public physx::PxCpuDispatcher
{
	virtual void submitTask(physx::PxBaseTask& task)
	{
		task.run();
		task.release();
	}
	virtual uint32_t getWorkerCount() const { return 1; }
};


class JobManager;
class Job
{
public:
	Job() = default;
	Job(const Job&);
	void Initialize(JobManager* parent, std::function<void(Job*)> function = std::function<void(Job*)>(), int refcount = 1);
	void Reset(int refcount = 1); //Call this before reusing a job that doesn't need to be reinitialized
	void Execute();
	void AddReference();
	void RemoveReference();
	void Wait(); //Block until job is finished
private:
	virtual void ExecuteInternal() {}

	std::function<void(Job*)> mFunction;
	JobManager* mParent;
	std::atomic_int mRefCount;

	bool mFinished;
	std::mutex mFinishedLock;
	std::condition_variable mFinishedEvent;
};

class JobManager
{
public:
	JobManager()
	{
		mWorkerCount = 8;
		mWorkerThreads = new std::thread[mWorkerCount];
		mQuit = false;

		for(int i = 0; i < mWorkerCount; i++)
			mWorkerThreads[i] = std::thread(JobManager::WorkerEntryPoint, this);
	}
	~JobManager()
	{
		if(!mQuit)
			Quit();
	}

	void Quit()
	{
		std::unique_lock<std::mutex> lock(mJobQueueLock);
		mQuit = true;
		lock.unlock();
		mJobQueueEvent.notify_all();
		for(int i = 0; i < mWorkerCount; i++)
		{
			mWorkerThreads[i].join();
		}
		delete[] mWorkerThreads;
	}

	template <int count, typename F>
	void ParallelLoop(F const& function)
	{
		/*for(int i = 0; i < count; i++)
			function(i);*/
		Job finalJob;
		finalJob.Initialize(this, std::function<void(Job*)>(), count);
		Job jobs[count];
		for(int j = 0; j < count; j++)
		{
			jobs[j].Initialize(this, [j, &finalJob, function](Job*) {function(j); finalJob.RemoveReference(); });
			jobs[j].RemoveReference();
		}
		finalJob.Wait();
	}

	static void WorkerEntryPoint(JobManager* parrent);
private:
	friend class Job;
	void Submit(Job* job);

	int mWorkerCount;
	std::thread* mWorkerThreads;

	std::mutex mJobQueueLock;
	std::queue<Job*> mJobQueue;
	std::condition_variable mJobQueueEvent;
	bool mQuit;
};

class MultithreadedSolverHelper
{
public:
	void Initialize(nv::cloth::Solver* solver, JobManager* jobManager);
	void StartSimulation(float dt);
	void WaitForSimulation();
private:
	Job mStartSimulationJob;
	Job mEndSimulationJob;
	std::vector<Job> mSimulationChunkJobs;

	float mDt;

	nv::cloth::Solver* mSolver;
	JobManager* mJobManager;
};