了解线程中的变量可访问性 [英] Understanding Variable Accessibility in Threads

查看:75
本文介绍了了解线程中的变量可访问性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解访问线程中的变量.经过一些研究,我发现了很多有关atomic的信息,效果很好!不过,我已经停滞不前,并希望在前进的过程中有所帮助.

I'm trying to get a better understanding of accessing variables in threads. After doing a little bit of research, I found a lot of info about atomic, which works great! I've come to a stand-still, though, and would like some help moving forward.

  • 我有两个类-一个类从文本文件读取以获取上次启动的信息以及其他每次启动所需的信息.这是一个单独的类,仅用于组织.读取的信息存储在原子变量中.

  • I have two classes - one class reads from a text file to grab information from last launch and other information I need for every launch. This is in a separate class just for organization. The info read is stored in atomic variables.

另一个类具有我所有的功能.这包括读取变量的信息,这些变量用于存储来自信息文件的信息.简而言之,该类继承了保存该信息文件的第一类变量.

The other class has all of my functions. This includes ones where it reads the variables used to store information that was from the information file. Simply put, this class inherits the first class the variables that hold that info file.

主要功能是在代码的开始处一起创建类对象 ,因为我需要该类中程序中其他部分的功能.初始设置(包括读取该信息文件)后,它将从需要在程序其余部分运行的第二类函数创建线程

The main function creates class objects at the very beginning of the code together because I need the functions within the classes for the other parts of the program. After the initial set up (including reading that info file), it creates threads from the second class functions that need to run for the rest of the program

为什么带有第二类功能的线程不能读取它从第一类继承的信息?

Why can the threads with functions from the second class not read the information it inherited from the first class?

  • 在创建线程之前,我已经读了很长时间.也许是因为第二个类继承了原始变量(都初始化为0),因为我在执行读取信息文件功能之前就声明了它?
  • 主函数中的变量读得很好.

.

#include "stdafx.h"
#include "Windows.h"
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<bool> timeToClose = false;

class first {
public:
    std::atomic<int> primary;
    void readFile() {
        primary = 1;
    }
    first() {
        primary = 0;
    }
};

class second: first {
public:
    void actionPrimary() {
        while (!timeToClose) {
            if (primary) {
                std::cout << "We ARE doing stuff here!\n";
                std::this_thread::sleep_for(std::chrono::milliseconds(1500));
            } else {
                std::cout << "We AREN'T doing stuff here!\n";
                std::this_thread::sleep_for(std::chrono::milliseconds(1500));
            }
        }
    }
};

int main() {
    first f;
    second s;
    f.readFile();
    std::thread threadActionPrimary([&s]() {
        s.actionPrimary();
    });
    while (!GetAsyncKeyState(VK_F1)) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    timeToClose = true;
    threadActionPrimary.join();
    std::cin.get();
}

编辑到凹凸:)

推荐答案

线程b何时可见线程a中的项目.

When does items in thread a become visible to thread b.

这与 cppreference:memory_order 有关.更改对第二个线程可见.

This is related to cppreference : memory_order. A change is visible to a second thread.

  • 线程A写入原子值(使用std::atomic)
  • 线程B读取原子值(使用std::atomic)
  • thread A wrote to an atomic value (using std::atomic)
  • thread B read the atomic value (using std::atomic )

还有一些与同步有关的更复杂的版本.

There are some more complex versions which relate to synchronization.

  • 线程A写入一些数据.
  • 线程A使用互斥锁或写入std :: atomic<<同步.
  • 线程B使用互斥锁或从std :: atomic读取
  • 线程B可以看到从线程A到同步为止的所有内存更改.

在这种情况下实际发生的是实例数据在类变量中.

What is actually happening in this case, is instance data in a class variable.

class MyBase {
    public:
       int BaseValue;
       MyBase() : BaseValue(10);
       void setValue( int v ) {
           BaseValue = v;
       }
};

class MyDerived : public MyBase {
      MyDerived() {}
};

 MyBase base;
 base.setValue( 12 );
 MyDerived derived;
 // derived.BaseValue = 10;
 // base.BaseValue = 12;  <<<< There are 2 different instances of the member BaseValue.

更新

每次创建变量;

Update

Each time you create a variable;

int i = 5;
int j = 10;

您创建了一个新的容器".如果您希望两个线程使用一个类(second?)进行通信,则需要创建一个容器,那么数据应该是可见的.

You create a new 'container' of things. If you want the two threads to communicate using one of the classes (second?) you need to create a single container, then the data should be visible.

但是要使其正常工作,您需要在2个线程之间进行某种形式的同步.

However to get it to work correctly, you need to have some form of synchronization between the 2 threads.

int main() {
    second s;
    s.readFile();
    std::thread threadActionPrimary([&s]() { // this acts as a synchronization point, so the thread sees all the changes to s that happened before this line.
        s.actionPrimary();
    });
    while (!GetAsyncKeyState(VK_F1)) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    timeToClose = true;
    threadActionPrimary.join();
    std::cin.get();
}

这篇关于了解线程中的变量可访问性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆