我寫了一個簡單的C++代碼來查找矢量的最小值,在下面找到。它在VC++和g ++上編譯,但在後者上運行到分段錯誤。如果我的代碼包含UB或g ++包含錯誤,我無法分辨。有人可以識別我的代碼中的任何錯誤嗎?線程示例,分段錯誤
segfault出現在thread :: join()處。
一些調試信息
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ??()
(gdb) where
#0 0x0000000000000000 in ??()
#1 0x00000000004688f7 in std::thread::join()()
#2 0x0000000000000000 in ??()
(gdb) thread
[Current thread is 1 (Thread 0x7c6880 (LWP 24015))]
下面是代碼
#include <iostream>
#include <random>
#include <thread>
#include <vector>
#include <algorithm>
using namespace std;
void find_min(vector<double>& x, double& min_val, int& min_id)
{
min_id = distance(x.begin(), min_element(x.begin(), x.end()));
min_val = x[min_id];
}
void find_part_min(vector<double>& x, vector<int>& min_ids, vector<double>& min_vals, int id)
{
int start_id = (x.size()*id)/min_vals.size();
int end_id = (x.size()*(id + 1))/min_vals.size();
for (int i = start_id; i < end_id; ++i)
{
if (x[i] < min_vals[id])
{
min_ids[id] = i;
min_vals[id] = x[i];
}
}
}
int main()
{
// define variables
int Nthreads = 16;
vector<double> x(256 * 256);
int min_id = 0;
double min_val = 0;
// fill up vector with random content
mt19937 gen(0);
uniform_real_distribution<> dis(0, 1);
generate(x.begin(), x.end(), bind(dis,gen));
// find min serial
find_min(x, min_val, min_id);
cout << min_id << "\t" << min_val << endl;
// initilaize variables for parallel computing
vector<double> min_vals(Nthreads, numeric_limits<double>::infinity());
vector<int> min_ids(Nthreads, -1);
vector<thread> myThreads;
for (int id = 0; id < Nthreads; ++id) // define each thread
{
thread myThread(find_part_min, ref(x), ref(min_ids), ref(min_vals), id);
myThreads.push_back(move(myThread));
}
for (int id = 0; id < Nthreads; ++id)
myThreads[id].join(); // part-calculations are finished
// merging the results together
min_val = numeric_limits<double>::infinity();
min_id = -1;
for (int i = 0; i < Nthreads; ++i)
{
if (min_vals[i] < min_val)
{
min_val = min_vals[i];
min_id = min_ids[i];
}
}
cout << min_id << "\t" << min_val << endl;
return 0;
}
診斷段錯誤時,獲取回溯並知道段錯誤發生的位置很有用。 – md5i
通過valgrind/helgrind運行它並沒有在linux/g ++上顯示任何問題 - 5.3 – Arunmu
從[未編譯的代碼]聲明運行時錯誤(http://coliru.stacked-crooked.com/a/19c20c61347e8a2f)聽起來怪怪的。 –