【发布时间】:2019-09-16 05:36:43
【问题描述】:
我是 C++ 新手,最近在研究并发性。 我尝试运行这个简单的程序来演示线程:
#include <vector>
#include <thread>
#include <stdio.h>
void threadWork()
{
printf("WORKER THREAD EXECUTING");
}
int main()
{
printf("INSTANTIATE THREAD\n");
std::vector<std::thread *> threadList;
threadList.push_back(&std::thread(&threadWork));
printf("THREAD INSTANTIATED JOINING...\n");
for (std::thread* t : threadList)
{
t->join();
}
printf("THREADS JOINED\n");
return 0;
}
在调用 push_back() 后,程序因调用 abort() 而崩溃(我在 Windows 上运行)
为什么这段代码在运行时会崩溃?
【问题讨论】:
-
为什么要保留一个指针的向量?你的指针指向什么?你懂指针吗?
-
不能取临时地址。
-
注:这甚至不会在 VS 之外编译
-
据我了解,添加到向量的指针指向实例化线程对象的地址(&std::thread(&threadWork))。我正在使用指针,因为我正在练习并且据我所知指针更灵活。
-
据我了解,指针更灵活 -- 不,这不是使用指针的理由。当你需要使用指针时,你就使用指针。
标签: c++ multithreading