【问题标题】:Modifying global variables from threaded functions and still run the main thread to use the Global varibales从线程函数修改全局变量并仍然运行主线程以使用全局变量
【发布时间】:2013-03-11 14:54:54
【问题描述】:

我在 Visual C++ 2010 中有一个项目,我必须在其中绘制一些圆圈和线条。圆的坐标取决于两个全局变量。全局变量由两个函数修改,每个函数都在自己的线程中运行。 Boost用于多线程。 但是,一旦我运行线程,我的主线程就会被阻塞,从而阻止我绘制形状和使用全局变量。我怎样才能解决这个问题?我最终想要实现的是,修改在各自线程中运行的两个单独函数的全局变量,并使用所述全局变量同时绘制圆圈

global_variable_1
global_variable_2

void function_1()
{
    while(true)
    {
    //modifies global_variable_1
    }
}

void function_2()
{
    while(true)
    {
    //modifies global_variable_2
    }
}

void MyOnPaint(HDC hdc)
{
    Graphics graphics(hdc);
    Pen pen(Color::Blue);

    /* Uses global_variable_1 & global_variable_2 to
    draw circles */
}

int APIENTRY _tWinMain(......)
{
    /* Some initial code */

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
    return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GAZEPOINTEVALUATION));

    /*Start threads*/
    using namespace boost;

    thread thread_1(function_1);

    thread thread_2(function_2);

    //Start threads
    thread_1.join()
    thread_2.join()

    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
        case WM_COMMAND:
            /* Some code */
        case WM_PAINT:
            hdc = BeginPaint(hWnd, &ps);
            /*CALL MY DRAWING METHOD*/
            MyOnPaint(hdc);   
            EndPaint(hWnd, &ps);
            break;
        case WM_DESTROY:
            /* Some code */
        default:
            /* Some code */
    }
    return 0;
}

【问题讨论】:

  • 由于线程问题,我不介意读取全局变量的脏值。忘了在问题中提到这一点。

标签: multithreading visual-studio-2010 visual-c++ boost gdi+


【解决方案1】:

join 调用将永远不会返回,因为您的线程将永远循环。来自docs:

为了等待执行线程完成,join(), 必须使用 boost::thread 对象的 __join_for 或 __join_until(不推荐使用 timed_join())成员函数。 join() 将阻止 调用线程,直到 boost::thread 表示的线程 对象已完成。

因此,您永远不会进入消息循环。

如果您删除连接调用,这应该会更符合您的预期 - 在更复杂的应用程序中,您需要正确设计线程调度和退出处理。即使是这样,您也可能不得不在生成的线程中添加一些延迟,以避免锁定 CPU 并可能看到其他您没有预料到的奇怪现象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多