Multiple threads problem - the thread can not get access global variable

  • Thread starter Thread starter hitbuyi
  • Start date Start date
H

hitbuyi

Guest
VS2015, MFC, code is below

typedef struct {
VCI_CAN_OBJ *pCanObj;
CString strTime;
int NumValue;
int kCanIndex;
}CANDispPara_t;

CANDispPara_t g_CANDispPara; // global variable

VCI_CAN_OBJ CANObj[2000]; // global variable

UINT CCANUSBDlg::ReceiveThread(void *param)
{

// get lot of data here, set set g_CANDispPara

g_CANDispPara.pCanObj = &CANObj[0];

g_CANDispPara.strTime = "12:34:56";

g_CANDispPara.NumValue = 10;

g_CANDispPara.kCanIndex = 1;

}

// display part of data 1
UINT CCANUSBDlg::DisplayThread_1(void *param)
{
VCI_CAN_OBJ *pCanObj;
CString strTime;
int NumValue;
int kCanIndex;

// get value of g_CANDispPara
pCanObj = g_CANDispPara.pCanObj; // g_CANDispPara is a gloabla variable
strTime = g_CANDispPara.strTime; // problem here!
NumValue = g_CANDispPara.NumValue; // problem here!
kCanIndex = g_CANDispPara.kCanIndex; // problem here!

}

// display part of data 2
UINT CCANUSBDlg::DisplayThread_2(void *param)
{
VCI_CAN_OBJ *pCanObj;
CString strTime;
int NumValue;
int kCanIndex;

// get value of g_CANDispPara
pCanObj = g_CANDispPara.pCanObj; // g_CANDispPara is a gloabla variable
strTime = g_CANDispPara.strTime; // problem here! global variable can to pass to local variable // strTime
NumValue = g_CANDispPara.NumValue; // problem here!
kCanIndex = g_CANDispPara.kCanIndex; // problem here!
}

the three threads are started as :

AfxBeginThread(ReceiveThread,0);

AfxBeginThread(DisplayThread_1,0);

AfxBeginThread(DisplayThread_2,0);

at dialogue initialization state and the ReceiveThread works well already.

Q1. I found pCanObj = g_CANDispPara.pCanObj; is right, pCanObj points to right address I assigned in CCANUSBDlg::ReceiveThread(void *param)
BUT strTime,NumValue, kCanIndex CAN NOT get value of g_CANDispPara.strTime, g_CANDispPara.NumValue,g_CANDispPara.kCanIndex respectively,
they are zeros! is it a problem on transfer data between threads? I think using global variable as a way of transfer data between threads is possible
Q2. I get a lot of data from CAN, period is 30ms, and foud it takes a lot of time to display the data on a list of placed in a dialogue, the thread_1 displays part1,
the thread_2 displays the part 2, is it possible?
Q3. The thread function can only be static class function? or it can be a common non-class function

Thanks.

Continue reading...
 
Back
Top