このコードは、以下のいずれかの行/* debug messages */
がコメント解除されている場合にのみ機能します。または、マップ先のリストが 30 要素未満の場合。
func_map
Lisp スタイルのマッピングの線形実装であり、動作すると想定できます。
使い方は以下のようになりますfunc_map(FUNC_PTR foo, std::vector* list, locs* start_and_end)
FUNC_PTR
ポインタを返しvoid
、受け取る関数へのint
ポインタです。
例: &foo
infoo
は次のように定義されます。
void foo (int* num){ (*num) = (*num) * (*num);}
locs
は 2 つのメンバーint_start
とint_end
;を持つ構造体です。これを使用して、func_map
反復する必要がある要素を伝えます。
void par_map(FUNC_PTR func_transform, std::vector<int>* vector_array) //function for mapping a function to a list alla lisp
{
int array_size = (*vector_array).size(); //retain the number of elements in our vector
int num_threads = std::thread::hardware_concurrency(); //figure out number of cores
int array_sub = array_size/num_threads; //number that we use to figure out how many elements should be assigned per thread
std::vector<std::thread> threads; //the vector that we will initialize threads in
std::vector<locs> vector_locs; // the vector that we will store the start and end position for each thread
for(int i = 0; i < num_threads && i < array_size; i++)
{
locs cur_loc; //the locs struct that we will create using the power of LOGIC
if(array_sub == 0) //the LOGIC
{
cur_loc.int_start = i; //if the number of elements in the array is less than the number of cores just assign one core to each element
}
else
{
cur_loc.int_start = (i * array_sub); //otherwise figure out the starting point given the number of cores
}
if(i == (num_threads - 1))
{
cur_loc.int_end = array_size; //make sure all elements will be iterated over
}
else if(array_sub == 0)
{
cur_loc.int_end = (i + 1); //ditto
}
else
{
cur_loc.int_end = ((i+1) * array_sub); //otherwise use the number of threads to determine our ending point
}
vector_locs.push_back(cur_loc); //store the created locs struct so it doesnt get changed during reference
threads.push_back(std::thread(func_map,
func_transform,
vector_array,
(&vector_locs[i]))); //create a thread
/*debug messages*/ // <--- whenever any of these are uncommented the code works
//cout << "i = " << i << endl;
//cout << "int_start == " << cur_loc.int_start << endl;
//cout << "int_end == " << cur_loc.int_end << endl << endl;
//cout << "Thread " << i << " initialized" << endl;
}
for(int i = 0; i < num_threads && i < array_size; i++)
{
(threads[i]).join(); //make sure all the threads are done
}
}
vector_locs[i]
問題は、スレッドの使用方法とスレッドの解決方法にあると思います。ただし、スレッドによって参照されるインスタンスの状態を維持するためにベクトルを使用すると、locs
それが問題になるのを防ぐことができます。私は本当に困惑しています。