I have the following situation for multithreading in C++:
Struct MyData
{
….
}
//Class to create a thread specific data
Class MiscData
{
public:
CList<CPtrArray, MyData*> myDataList;
HANDLE m_dbHanle;
String m_SQLCmd;
MiscData ()
{
m_dbHandle = DatabaseConnect(connection parameters);
}
inline FillMyDataList(MyData* data)
{
myData* pData = allocate memory;
pData = data;
myDataList.Add(pData);
}
BuildSQLCmd(string str)
{
m_SQLCmd .Format(“…”, str);
}
}
Global Methods:
Void GetMyDataFromDB(MiscData* pMiscData)
{
pMiscData->ByuldSQLCmd(_T(“Select * from myTable”));
BuildDataFromDB(pMiscData);
//Access MyData structure from pMiscData->myDataList
}
BuildDataFromDB(MiscData* pMiscData)
{
int nReturn;
ExecuteSQLCMD(pMiscData, &nReturn);
While(recordsin table)
{
myData.x=record.columnValue
pMiscData-> FillMyDataList(&myData);
}
}
Int ExecuteSQLCMD(MiscData* pMiscData, int* nReturn)
{
String tablename = Extract Table name from pMiscData->m_SQLCmd;//SQL query
Calls SQLExecDirect(pMiscData->m_SQLCmd)
…
}
ThreadFunction(void* pParam)
{
MiscData* pThreadData = (MiscData*) pParam;
}
main()
{
MiscData pMiscData1 = new MiscData(); //Thread specific data
MiscData pMiscData2 = new MiscData();//Thread specific data
MiscData pMiscData3 = new MiscData();//Thread specific data
//Handle hT1 = createthread()
Unsigned uiThreadId;
Handle hT1 = _beginThreadex(NULL,
0,
ThreadFuntion,
pMiscData1,
CREATE_SUSPENDED,
& uiThreadId);
Handle hT2 = _beginThreadex(NULL,
0,
ThreadFuntion,
pMiscData2,
CREATE_SUSPENDED,
& uiThreadId);
Handle hT3 = _beginThreadex(NULL,
0,
ThreadFuntion,
pMiscData3,
CREATE_SUSPENDED,
& uiThreadId);
ResumeThread(hT1);
ResumeThread(hT2);
ResumeThread(hT3);
WaitForSingleObject(ht1,INFINITE);
WaitForSingleObject(ht2,INFINITE);
WaitForSingleObject(ht3,INFINITE);
}
All threads have same thread function. Thread function in turn calls different methods, which in turn calls other methods. In all the methods a thread specific data (pMiscData) is passed.
My questions are:
(1)Creating thread specific data (pMiscData1, pMiscData2, pMiscData3)and passing them separately to each thread, does it make really a thread specific data and is only available to its respective thread?
(2)As all threads can enter a method simultaneously, so threads can preempt each other, if so what would happen to the data in the thread specific data (pMiscData1)?
(3)After pre-empting, if a thread returns back, does it start from wherever it was left off?
(4)Other than creating thread specific objects in the main thread and passing them to their respective threads(while creating thread), I do not have any global or static variables, so my above program is a thread safe?
Please suggest me what I am doing wrong.
Sorry for the long message, sorry for any confusion. I am happy to answer any questions.
Thanks for your time & suggestions in advance.
Thanks again.
-BubblesM