[英]Problem with using WINAPI threads in Qt in C++
我被分配创建一个程序来处理三个 WINAPI 线程并反映那些正在进行的条的工作流。 我决定将 Qt 小部件用于这些目的。 我使用CREATE_SUSPENDED
创建标志在暂停的 state 中创建这些线程,然后单击按钮后使用ResumeThread
function 恢复它。 当我单击它时,程序会因未处理的 win32 异常而崩溃。 为什么会发生这种情况?
我的“创建”按钮单击槽
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();
}
}
我的线程function
DWORD WINAPI MainWindow::ThreadFunc1(LPVOID lpParams)
{
for(int i = 0; i < 100; i++)
{
ui->progressBar->setValue(i);
sleep(500);
}
return 0;
}
其他2个线程功能相同,只是使用了不同的进度条。
您正在从非 ui 线程访问 ui 设备。 这将导致竞争条件。 为了安全地做你想做的事,你需要将 QEvents 发布到 ui 线程。 或者使用 QThread 和信号和槽可以实现同样的事情。
看来您正在传递一个成员 function 指针作为应该执行的 function 。 Remember that you can't call a member function without an object instance that "performs" the function call, except for static member functions.
请参阅此线程以获取解决方法: 您如何将 CreateThread 用于 class 成员的函数?
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.
编辑:
请参阅“返回值”下的 CreateThread 的 Microsoft 文档:
请注意,即使 lpStartAddress 指向数据、代码或不可访问,CreateThread 也可能成功。 如果线程运行时起始地址无效,则发生异常,线程终止。 由于起始地址无效而导致的线程终止被视为线程进程的错误退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.