gpt4 book ai didi

c++ - thread.join 期间出现段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:17 24 4
gpt4 key购买 nike

我的代码有问题。当我将 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 万亿 bool 值的数组,并且我之前使用单线程程序执行过此操作。分配时不会出现错误!我有足够的内存。它发生在线程管理的某处

最佳答案

好的,我在我的调试器中运行了这段代码(在重新安排函数顺序并添加缺少的包含文件以便编译之后)。

对我来说,段错误发生在程序的末尾。我强烈怀疑这个函数中的逻辑不正确:

bool threads_finished(std::thread *threads)
{
for (int t = 0; t < NUM_THREADS; t++)
if (!threads[t].joinable())
return false;
return true;
}

有两个原因:

  1. 如果任何线程不可加入,您将返回 false(即不,未完成),并且

  2. 您无法像这样检测线程是否已完成。您需要让线程更新原子计数器/标志集或更好,一个由条件变量和互斥锁对保护的标志集,以便您可以正确地(a)测试线程是否完成以及(b)等待所有线程完成在 main() 结束之前完成。

更新:

根据要求添加引用。建议您将此站点添加为书签。

A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

http://en.cppreference.com/w/cpp/thread/thread/joinable

关于c++ - thread.join 期间出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com