这是函数execute(),用于一些指令:
void execute() {
while (run) { //thread is running
if (time % 3 == 0) { // execute instructions when clock is 3
Instruct Instr;
uint16_t src1 = 0;
uint16_t src2 = 0;
int target_cycle = time;
while (target_cycle > time) {
std::this_thread::sleep_for(thread_sleep);
}
while (hpp_DE_EX.size() != 0) {
Instr = hpp_DE_EX.front();
hpp_DE_EX.pop();
uint16_t instr = Instr.header;
ptrLog->PrintData(get, instr);
src2 = instr & 0x1F;
src1 = (instr >> 0x5) & 0x1F;
uint16_t opcode = (instr >> 0xA) & 0x3F;
....
}
//For running this thread:
auto exThread = std::thread(&processor::execute, this);
exThread.detach();
使用这个函数execute(),我想创建多个线程实例。我认为这是声明线程的可能性(但是当我编写此代码时,我收到一些错误 - INVOKE ERROR C2672)---已修改,现在正在工作
std::vector<std::thread> threads;
for (int i = 0; i <= 5; i++) // need 5 instances
threads.push_back(thread(&processor::execute, this));
cout << "Synchronizing all threads...\n";
for (auto& th : threads) th.join(); // Running code
我的目的是使用execute()函数(线程)来执行并行指令而不是线性指令 - 可函数参数。
谢谢,F。
最佳答案
假设processor::execute
是一个没有参数的静态成员函数,那么你向它传递一个额外的参数,这样std::thread
实现就找不到具有正确参数的重载。正确的调用是:
threads.push_back(thread(&processor::execute));
或更简单地说:
threads.emplace_back(&processor::execute);
如果它不是静态方法,那么您需要传递处理器类的实例,例如:
processor p;
for (int i = 0; i <= 5; i++)
{
threads.emplace_back(&processor::execute, &p);
}
通过打印“同步所有线程”
来判断,我认为您不明白std::thread::detach
的作用,它将线程与分离>std::thread
实例,以便在结构被破坏后它可以继续运行。我假设您实际上打算调用 std::thread::join 来等待线程完成执行。 std::thread::detach
很少是正确的做法。
关于c++ - 如何使用同一个函数C++实例化多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762699/