2013-03-11 67 views
0

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

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; 
} 
+0

因为线程问题,我不介意读全局变量的脏值。忘了在提问中提到这一点。 – SParanagama 2013-03-11 15:02:00

回答

2

join调用将永远不会返回画出的圆圈,因为你的线程循环,直到永远。从docs

为了等待执行线程来完成,该连接(), __join_for或__join_until(timed_join()不建议使用)的线程对象的成员函数必须使用。 join()会阻塞 调用线程,直到boost :: thread 对象表示的线程完成。

因此,您从不输入消息循环。

如果您删除了联接调用,这应该会更像您所期望的 - 在更复杂的应用程序中,您需要正确设计线程调度和退出处理。即使是这样,你也可能不得不在产生的线程中加入一些延迟,以避免钉住CPU,并可能看到其他你不期待的怪异。