最近は、Windows のスレッドについてもっと学ぼうとしています。私はこの実用的なアプリケーションを作ることを考えました:
「開始」ボタンが押されたときにいくつかのスレッドが開始されたとします。これらのスレッドが集中的であると仮定します (実行し続けているか、常に何らかの作業を行っています)。
このアプリには「停止」ボタンもあります。このボタンが押されると、すべてのスレッドが適切な方法で閉じられるはずです。つまり、リソースを解放し、作業を放棄して、[開始] ボタンが押される前の状態に戻ります。
アプリのもう 1 つの要求は、スレッドによって実行される関数に、「停止」ボタンが押されたかどうかを確認する命令を含めないようにすることです。スレッドで実行されている関数は、停止ボタンを気にする必要はありません。
言語: C++
OS: Windows
問題:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
スレッドを適切に停止できるようにするには、ラッパー関数をどのように作成すればよいですか? ( TerminateThread やその他の関数を使用せずに)
プログラマがメモリを動的に割り当てたらどうなるでしょうか? スレッドを閉じる前にそれを解放するにはどうすればよいですか?(「停止ボタン」を押してもスレッドはまだデータを処理していることに注意してください) new 演算子をオーバーロードするか、メモリを動的に割り当てるときに使用される事前定義された関数の使用を強制することについて考えました. ただし、これは、この 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,...);