【发布时间】:2015-10-19 17:36:04
【问题描述】:
我的代码有问题。当我将 argv[1] 增加到 4.294.967.295 (INT_MAX) 时,我遇到了分段错误,尽管我选择了“long long int”作为数据类型:
#define NUM_THREADS 5
// ...
int main (int argc, char **argv)
{
// allocating memory and declaring threads
std::thread thread[NUM_THREADS];
bool *sv_ptr = (bool *) calloc(atoll(argv[1]), sizeof(bool));
short int t = 0;
long long int i = 2;
// initialize threads
for (t = 0; t < NUM_THREADS; t++, i++)
thread[t] = std::thread(remove_multiples, i, sv_ptr, atoll(argv[1]));
t = 0;
while (i < atoll(argv[1]) || !threads_finished(thread))
{
if (sv_ptr[i] || thread[t].joinable())
{
// starting new tasks
if (thread[t].joinable())
{
thread[t].join(); // <- segfault occurs here
thread[t] = std::thread(remove_multiples, i, sv_ptr, atoll(argv[1]));
}
// printing results
if (!sv_ptr[i-NUM_THREADS])
std::cout << (i - NUM_THREADS) << std::endl;
i++;
}
// increment thread iterator
t = (t + 1) % NUM_THREADS;
}
// ...
}
void remove_multiples(long long int n, bool *sv_ptr, long long int max)
{
for (int i = 2; i*n < max; i++)
sv_ptr[i*n] = true;
}
bool threads_finished(std::thread *threads)
{
for (int t = 0; t < NUM_THREADS; t++)
if (!threads[t].joinable())
return false;
return true;
}
在加入可连接线程时发生分段错误。
感谢您的帮助!
编辑:我想在我的 16 GB 机器上测试堆分配,因此我编写了这个程序。我能够创建一个约 1.5 万亿布尔值的数组,并且我之前使用单线程程序做到了这一点。 分配时不会发生错误!我有足够的内存。它发生在线程管理中的某个地方
【问题讨论】:
-
此代码段仅用于初始化所有 NUM_THREADS 个线程。我在 while 循环中遍历数组。
-
bool *sv_ptr = (bool *) calloc(atoll(argv[1]), sizeof(bool));我希望您使用 64 位并拥有大量 RAM,考虑到这将分配至少 4 GB,也许 16 GB。确定是这样吗? -
旁注:尽可能保持变量在本地(就声明和使用而言)(例如:for(short int t = 0; ...))并避免在不同的环境中循环使用变量上下文。
-
我想测试堆分配,因此我想使用我的整个内存(16 GB)
-
@J.Doe,你试过调试你的程序吗?访问哪个地址会导致段错误?我在您的程序中看到至少一个潜在的段错误:
calloc失败并返回 NULL,其中一个线程抓住它并尝试访问remove_multiples。繁荣。段错误。
标签: c++ multithreading c++11