如何确保线程获取线程内部使用的变量的更新值?

问题描述 投票:0回答:1

我正在处理 dll 情况,并希望线程从启动时不断运行。该线程使用在该线程外部定义的布尔值和其他变量。当我更新值时,程序的其余部分已更新值,但线程本身没有更新值,而是使用默认值。

内部.cpp

bool Linked = false;
int RedSlot = 1;

void ThisFunction(longlong param_1)
{
'''
}

void TheRedButton()
{
    while (true)
    {
                printf("Connected: %s\n", &Linked ? "true" : "false");
                        '''
                        printf("Red Slot: %i", RecordingSlot);

        }
}

extern "C" __declspec(dllexport) void ChangeRedSlot(int RedCSlot)
{
    RedSlot = RedCSlot;
}


dllmain.cpp

void OnInitializeHook()
{
'''
        CreateThread(NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(TheRedButton), 0, NULL, 0);
'''
}

我有一个正在运行的控制台屏幕,它总是打印出线程中变量的值,并且它们永远不会改变。

我调试了程序,如上所述,线程运行,但变量根本不更新线程内的值,尽管变量在程序中的其他地方更新了。我还尝试使用带有 bool 变量的指针,但由于某种原因该指针总是返回相同的值;即使实际值发生变化。

如果无法让线程始终具有更新的变量,是否有其他解决方案来实现我想要实现的目标?

c++ dll-injection
1个回答
0
投票

正确执行线程处理涉及许多需要恰到好处的细节。

  • 没有全局变量(无论如何总是糟糕的设计)
  • 线程安全初始化
  • 关机时的正确行为

这是把事情做好的“穷人”版本。 使用条件变量更好的解决方案

#include <thread>
#include <atomic>
#include <chrono>

using namespace std::chrono_literals;

// model your global state
struct global_data_t
{
    // allow thread to stop cooperatively (or you face race conditions at shutdown!)
    std::thread thread;
    std::atomic<bool> stop_thread = false;  

    // "global" data
    bool Linked = false;
    int RedSlot = 1;

    // at shutdown make sure thread is stopped too!
    ~global_data_t()
    {
        if (thread.joinable())
        {
            thread.join();
        }
    }
};

// Meyer's singleton
// since C++11 the initialization of static local variable
// is guaranteed to be threadsafe!
global_data_t& get_global_data()
{
    static global_data_t data;
    return data;
}

// use C++'s thread + lambda expression for its function
void OnInitializeHook()
{
    auto& global_data = get_global_data();
    global_data.thread = std::thread{[&]
    {
        while (!global_data.stop_thread)
        {
          // loop code here 
        }
    }};
}

int main()
{
    OnInitializeHook();

    std::this_thread::sleep_for(500ms);

    get_global_data().stop_thread = true;

}
© www.soinside.com 2019 - 2024. All rights reserved.