据我从代码中可以看出,您将拥有start_task_proc
在其调用堆栈中的某个位置调用其函数对象的线程。您可以修改该函数以获取指向“任务信息”结构的指针,而不是裸函数对象。您可以将您喜欢的任何信息填充到该信息对象中,例如您创建任务的行号和文件名:
template <class T>
struct TaksInfo {
T func;
unsigned line;
char const* file;
TaskInfo(T&& t, unsigned l, char const* f)
: func(std::move(t), line(l), file(f) {}
};
template<typename T>
smart_ptrs::w32handle StartTask(T f, unsigned line, char const* file)
{
// Make a copy of the task on the heap
auto pTask = new TaskInfo<T>(f, line, file);
// Create a new thread to service the task
smart_ptrs::w32handle hThread(::CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)& detail::start_task_proc<T>,
(LPVOID) pTask,
NULL,
NULL));
// If the caller ignores this rc, the thread handle will simply close and the
// thread will continue in fire-and-forget fashion.
return hThread;
}
#define START_TASK(f) StartTask(f, __LINE__, __FILE__)
template <class T>
DWORD start_task_proc(LPVOID lpParameter) {
auto pTask = (TaskInfo<T>*) lpParameter;
return pTask->func();
}
//use:
int main() {
auto threadHandle = START_TASK(([]() -> DWORD { std::cout << "foo\n"; return 42;} ));
}
如果您现在检查pTask
,start_task_proc
您可以看到file
并且line
可以告诉您任务从哪里开始。
当然,您可以避免TaskInfo
结构并使信息只是以下模板参数start_task_proc
:
template <class T, unsigned Line, char const* File>
DWORD start_task_proc(LPVOID lpParameter) { /* as you have it */)
template<unsigned Line, char const* File, typename T> //use T last fur type deduction
smart_ptrs::w32handle StartTask(T f)
{
// Make a copy of the task on the heap
auto pTask = new T(std::move(f));
// Create a new thread to service the task
smart_ptrs::w32handle hThread(::CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)& detail::start_task_proc<T, Line, File>, //!!!
(LPVOID) pTask,
NULL,
NULL));
// If the caller ignores this rc, the thread handle will simply close and the
// thread will continue in fire-and-forget fashion.
return hThread;
}
#define START_TASK(f) StartTask<__LINE__, __FILE__>(f)