c++ - 如何使用同一个函数C++实例化多个线程

标签 c++ multithreading multiple-instances

这是函数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/

相关文章:

c++ - 有没有办法优化这段代码?

c++ - 如何增长 GL_TEXTURE_2D_ARRAY?

c++ - switch 语句未检测到某些字符

mysql - 是否可以在mysql中同时运行多个用分号分隔的更新语句?

JavaScript 多实例

android - android中媒体播放器问题的多个实例

c# - 如何在 EmguCV 中使用 C# 中的迭代器?

C++ 线程库,在完成前两个后启动线程

python - 终止 PyQt 应用程序中长时间运行的 Python 命令

java - RxJava 无法在未调用 Looper.prepare() 的线程内创建处理程序