我有以下代码(我是线程世界中的新手),我不知道为什么它不起作用,因为我发现将args传递给线程的正确方法与我完全相同d ... 因此,如果有人可以提供帮助,也许你们中的一个可以向我推荐一些有关c ++中线程的摘要或
#include <iostream>
#include <thread>
#include <mutex>
#include <Windows.h>
#include <vector.hpp>
#include <functional>
void gotoxy(short, short);
void printAt(const char*, eestl::vector<int>&, short, short);
int main(int argc, char** args) {
eestl::vector<int> Odd{ 1,3,5,7,9 };
eestl::vector<int> Even{ 0,2,4,6,8 };
const char* odd_p = "Odd values: ";
short odd_x = 2;
short odd_y = 3;
const char* even_p = "Even values: ";
short even_x = 2;
short even_y = 13;
std::thread t1{ printAt, odd_p, Odd, odd_x, odd_y};
std::thread t2{ printAt, even_p, Even, even_x, even_y };
t1.join();
t2.join();
return 0;
}
void gotoxy(short x, short y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void printAt(const char* msg, eestl::vector<int>& v, short x = 0, short y = 0) {
static std::mutex m;
gotoxy(x, y);
printf("%s", msg);
for (auto a : v) {
m.lock();
printf("%d, ", a);
Sleep(1000);
m.unlock();
}
}
如果有人要“ vector.hpp”,这也是我自己实现的vector,问题就不存在,因为我可以用std :: vector替换eestl :: vector,而错误是一样...
答案 0 :(得分:4)
来自cppreference.com's std::thread
constructor page:
如果需要将引用参数传递给线程函数,则必须将其包装(例如,使用
std::ref
或std::cref
)。
也就是说:
std::thread t1{ printAt, odd_p, std::ref(Odd), odd_x, odd_y };
std::thread t2{ printAt, even_p, std::ref(Even), even_x, even_y };