Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 何时在C+中使用QMutex+;Qt?_C++_Multithreading - Fatal编程技术网

C++ 何时在C+中使用QMutex+;Qt?

C++ 何时在C+中使用QMutex+;Qt?,c++,multithreading,C++,Multithreading,我有两个场景,我不知道是否应该使用QMutex。 我已经多次在没有QMutex的情况下运行该程序&它没有显示任何异常行为。为了简单起见,我在这里略过了代码。 但为了安全起见,我想知道是否应该使用QMutex 场景#1: class A : QObject { Q_OBJECT private double **array;//it is initialised in the constructor & is 100x100 slots:

我有两个场景,我不知道是否应该使用
QMutex
。 我已经多次在没有QMutex的情况下运行该程序&它没有显示任何异常行为。为了简单起见,我在这里略过了代码。 但为了安全起见,我想知道是否应该使用
QMutex

场景#1:

 class A : QObject
 {
    Q_OBJECT

    private double **array;//it is initialised in the constructor & is 100x100

    slots:
          slot1(); //2 Qthreads are created in my main GUI thread along with 2 objects of class A, & by A aobj.movetothread();
          slot2(); //& connecting these 2 slots to started() SIGNAL of respective QThread's
                   //I have multi-threaded my application.
 }

 A::slot1()
 {
    double temp = array[i][j];
    //some operations on temp
 }

 A::slot2()
 {
    double temp = array[i][j];
    //some operations on temp
 }
注意:
array[][]
的内容在初始化后不会更改。我只在两个线程中访问它的信息。但是,有时两个线程可能同时访问
数组
中的同一元素

场景#2

 A::slot1()
 {
    double temp = somefunc();
    array[0][j] = temp;
 }

 A::slot2()
 {
    double temp = somefunc();
    array[50][j] = temp;
 }

注意:在这种情况下,两个线程修改同一数组中的元素,但是它们不修改/访问公共元素,即thread1处理前50行,而thread2处理后50行,但是它们甚至不访问彼此的行。

如果这些场景不同时运行,则不需要互斥锁。访问从两个线程中读取的数据是可以的,在两个(甚至更多线程)中修改同一数组中的不同元素也是可以的。当两个线程修改数组中的同一个元素时,或者当您从一个线程修改同一个元素而从另一个线程读取它们时,您需要互斥体的情况下,您的两个场景是否同时运行?它们似乎都不需要互斥锁本身,但如果它们同时执行,那么您需要在scenario2和scnario1之间进行同步—假设您从第一个场景访问一些数据,而第二个场景将数据写入同一行。您可能会读取一半的实际数据和另一半的更新数据,这可能会破坏一致性(这取决于实际代码,不过,您需要自己决定,是否可以)。不,它们是单独的情况!它们不会同时发生!