如何使用相同的函数 C++ 实例化多个线程

How to instantiate multiple threads using the same function C++

这里是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);

如果它不是静态方法,那么您需要传递处理器实例 class,例如:

processor p;
for (int i = 0; i <= 5; i++)
{
    threads.emplace_back(&processor::execute, &p);
}

通过打印判断 "Synchronizing all threads" 我想你不明白 std::thread::detach 做了什么,它将线程从 std::thread 实例中分离出来,以便它可以继续 运行一旦结构被破坏。我假设您实际上打算调用 std::thread::join 等待线程完成执行。 std::thread::detach 很少是正确的做法。