std::thread只允许一个参数



我正在尝试在C++中使用std::thread。我的问题是它只允许一个参数(目标函数(。这意味着我不能将参数传递给线程。我不知道为什么。这是我的密码。

#include <thread>
#include <iostream>
void run_thread(int num) {
std::cout << num << std::endl;
}
int main() {
std::thread t(run_thread, 5);
return 0;
}

这是错误消息。

test.cpp:9:17: error: no matching constructor for initialization of 'std::thread'
std::thread t(run_thread, 5);
^ ~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:340:9: note: 
candidate constructor template not viable: requires single argument '__f', but 2
arguments were provided
thread::thread(_Fp __f)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:220:5: note: 
candidate constructor not viable: requires 1 argument, but 2 were provided
thread(const thread&);
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:227:5: note: 
candidate constructor not viable: requires 0 arguments, but 2 were provided
thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
^
1 error generated.

我运行了g++ -o test test.cpp行来编译它。我使用的是苹果设备。这是gcc -v的输出

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.21)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

有人能告诉我发生了什么事吗?

它只允许一个参数(目标函数(-这似乎是错误的。。它可以允许更多,有关更多信息,请查看cpprreference函数的参数是可变的,而不是固定的

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );

试试这个

如果尚未完成,请确保使用-std=c++11进行编译

#include <iostream>
#include <utility>
#include <thread>
#include <chrono> 

void f1(int n, int n2)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread  executing "  << n2 << "n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int n, int n2, int n3)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread  executing "  << n2  << " " << n3 << "n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int x = 5, extra = 7, extra2 = 9;
std::thread t1(f1, x, extra);
t1.join();
std::thread t2(f2, x, extra, extra2);
t2.join();
return 0;
}

在这种情况下,您可以使用lambda:

std::thread t( []() { run_thread(5); } );

投诉后,它不起作用,我写道:

#include <iostream>
#include <thread>
using namespace std;
void someMethod(int value) {
cout << "someMethod(" << value << ")" << endl;
}
int main(int, char **) {
thread t([]() { someMethod(5); });
t.join();
cout << "Done." << endl;
}

然后我做了这个:

g++ -std=c++17 Foo.cpp -o Foo && Foo
someMethod(5)
Done.

我不知道什么不管用。

最新更新