在C ++中的Qt中使用WINAPI线程的问题

I was assigned to create a program that handles three WINAPI threads and reflects the workflow of those in progress bars. I decided to use Qt Widgets for these purposes. I create those threads in suspended state, using CREATE_SUSPENDED creation flag, then i resume it with ResumeThread function upon clicking the button. When I click it, the program crashes with an unhandled exception win32. Why could this happen?

我的“创建”按钮点击位置

void MainWindow::on_pb_create_clicked()
{
    hThread[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc1, NULL, CREATE_SUSPENDED, &thID[0]);
    hThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc2, NULL, CREATE_SUSPENDED, &thID[1]);
    hThread[2] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc3, NULL, CREATE_SUSPENDED, &thID[2]);
    threadsCreated = true;
}

我的“开始”按钮点击位置

void MainWindow::on_pb_start_clicked()
{
    if(threadsCreated)
    {
       for(int i = 0; i = 2; i++)
       {
           ResumeThread(hThread[i]);
       }
    }
    else
    {
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText("Threads are not created");
        msg.exec();
    }
}

我的线程功能

DWORD WINAPI MainWindow::ThreadFunc1(LPVOID lpParams)
{
    for(int i = 0; i < 100; i++)
    {
        ui->progressBar->setValue(i);
        sleep(500);
    }
    return 0;
}

其他2个线程功能相同,只是使用不同的进度条。

评论
  • Basil
    Basil 回复

    您正在从非ui线程访问ui设备。这将导致竞争状况。为了安全地执行您想做的事情,您将需要将QEvents发布到ui线程。或者使用QThread,信号和插槽可以实现相同的目的。

  • 小鸡鸡
    小鸡鸡 回复

    似乎您正在传递成员函数指针作为应执行的函数。 请记住,除了静态成员函数之外,没有没有“执行”函数调用的对象实例就不能调用成员函数。

    See this thread for a workaround: How do you use CreateThread for functions which are class members?

    Bottom line is you call a static member function, pass it the object that should perform some member function call (your MainWindow instance in this case), then the instance performs the call.