这些天,我想了解更多有关线程在Windows中的东西。我想到了这个实际应用:C++ winapi线程
假设按下按钮“开始”时有多个线程启动。假设这些线程是密集的(他们继续运行/总是有一些工作)。
这个程序也会有一个“停止”按钮。当按下这个按钮时,所有的线程都会以一种很好的方式关闭:释放资源并放弃工作并返回按下“开始”按钮之前的状态。
该应用程序的另一个要求是,如果按下“停止”按钮,线程运行的函数不应包含任何指令检查。线程中运行的函数不应该关心停止按钮。
语言:C++
操作系统:Windows
问题:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
我应该如何构建包装函数,这样我可以正确地停止线程? (不使用TerminateThread或其他功能)
如果程序员动态地分配一些内存会怎么样?我怎么才能在关闭 线程之前释放它?(注意,当我按下“停止按钮”时,线程仍在处理数据) 我虽然关于重载新操作符或只是强加使用预定义的 函数来使用动态分配内存。但是,这意味着 使用此API的程序员受到限制,而这不是我想要的。
谢谢
编辑:骷髅来形容,我想实现的功能。
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
(free memory allocated dynamically etc)
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
考虑使用'volatile'关键字来防止编译器导致布尔值被缓存并保存在一个寄存器中,从而防止线程中的值发生变化。 – 2012-06-14 10:26:50
问题是我想让用户不关心在线程函数中停止,只需编写功能。 –
@infact好主意,完成。 –