在网站上:godbolt.org,只有在那里:我如何使用 std::thread?
On the website: godbolt.org, and only there: how can I use std::thread?
这是我的代码:
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
#include <iostream>
void f(int n)
{
for (int cnt = 0; cnt < n; ++cnt) {
std::this_thread::sleep_for(1s);
std::cout << "." << std::flush;
}
std::cout << std::endl;
}
int main()
{
std::thread t1 = std::thread(f, 5);
//t1.join();
t1 = std::thread(f, 5); // <- should abort if t1.join() is not done
t1.join();
}
对于该网站,我正在使用 gcc9.2 执行程序来查看当未加入的线程被破坏时会发生什么,但这是编译器输出选项卡的内容:
Could not execute the program
Compiler returned: 1
Compiler stderr
/tmp/ccjlEO57.o: In function `std::thread::thread<void (&)(int), int&, void>(void (&)(int), int&)':
/opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
此外 - 当我将“-lpthread”添加到 编译器选项... 编辑框时,我得到一个不同的错误:
Program returned: 255
Program stderr
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
请注意,对于第二个 运行,第一个 t1.join()
没有被注释掉(所以它应该 运行 没问题)。
这是否意味着您无法在非常棒的 godbolt.org 网站上测试任何 std::thread
相关内容?
很有可能,线程创建在 godbolt.org 上是有意禁用的(以防止拒绝服务攻击或其他滥用),因此目前无法在该服务上使用 std::thread。
站点 now 支持线程。将 -pthread
添加到编译器参数。
这是我的代码:
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
#include <iostream>
void f(int n)
{
for (int cnt = 0; cnt < n; ++cnt) {
std::this_thread::sleep_for(1s);
std::cout << "." << std::flush;
}
std::cout << std::endl;
}
int main()
{
std::thread t1 = std::thread(f, 5);
//t1.join();
t1 = std::thread(f, 5); // <- should abort if t1.join() is not done
t1.join();
}
对于该网站,我正在使用 gcc9.2 执行程序来查看当未加入的线程被破坏时会发生什么,但这是编译器输出选项卡的内容:
Could not execute the program
Compiler returned: 1
Compiler stderr
/tmp/ccjlEO57.o: In function `std::thread::thread<void (&)(int), int&, void>(void (&)(int), int&)':
/opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
此外 - 当我将“-lpthread”添加到 编译器选项... 编辑框时,我得到一个不同的错误:
Program returned: 255
Program stderr
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
请注意,对于第二个 运行,第一个 t1.join()
没有被注释掉(所以它应该 运行 没问题)。
这是否意味着您无法在非常棒的 godbolt.org 网站上测试任何 std::thread
相关内容?
很有可能,线程创建在 godbolt.org 上是有意禁用的(以防止拒绝服务攻击或其他滥用),因此目前无法在该服务上使用 std::thread。
站点 now 支持线程。将 -pthread
添加到编译器参数。