简体   繁体   English

QtConcurrentRun和互斥锁的非常简单的方法有时会给出分段错误

[英]Very simple method with QtConcurrentRun and mutex sometimes gives segmentation fault

I want to know what is wrong with this code. 我想知道这段代码有什么问题。 Sometimes I get sementation fault, sometimes not. 有时我会出现固立错误,有时不会。 This is a problem that I have in a greater piece of software, the idea is that just one thread at the same time is executing the method MyClass::print. 这是我在更大的软件中遇到的一个问题,它的想法是同时只有一个线程正在执行方法MyClass :: print。 Even with this simple example, it fail with segmentation fault. 即使使用这个简单的示例,它也会因分段错误而失败。 What is wrong in the code? 代码有什么问题? How I can solve the problem? 我该如何解决这个问题?

Thanks! 谢谢!

#include <iostream>
#include <ctime>
#include <QMutex>
#include <QtConcurrentRun>

class MyClass : QThread {
public:
    void print(std::string str) {
        mutex.lock();
        std::cout << "In some thread: " <<  str << "\n";
        mutex.unlock();
    }

private:
    QMutex mutex;

};

int main() {

    MyClass myCl;

    for(int i=0; i < 10; i++) {
        QtConcurrent::run(&myCl, &MyClass::print,std::string("bla"));
    }

}

You do not join your threads after the for cycle that spawns them. 在产生它们的for循环之后,您不加入线程。

Therefore, the main() function may end before all the threads have finished. 因此, main()函数可能在所有线程完成之前结束。 This would make myCl go out of scope, and the threads would be trying to access an object that has been destroyed (in particular, its mutex variable). 这将使myCl超出范围,并且线程将尝试访问已被破坏的对象(尤其是其mutex变量)。 Which gives you Undefined Behavior . 这给你未定义的行为

Things should get better if you joined your threads before exiting from main() (or find any other way of not exiting from main() as long as any of the threads is still running). 如果您在退出main()之前加入线程(或者找到任何其他不退出main() ,只要任何线程仍在运行),情况将会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM