[問題] 有關VC上多執行緒的問題
看板C_and_CPP作者slimbody15 (~只愛Leah Dizon~)時間13年前 (2010/11/22 22:03)推噓7(7推 0噓 17→)留言24則, 4人參與討論串1/2 (看更多)
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 )
( 未必需要依照此格式,文章條理清楚即可 )
遇到的問題: (題意請描述清楚)
小弟用VC寫一個多執行緒的視窗程式,程式是寫入檔案的應用,
我寫了5個work function,
第一個work function為寫入10個1到txt檔
第二個work function為寫入10個2到txt檔
第三個work function為寫入10個3到txt檔
第四個work function為寫入10個4到txt檔
第五個work function為寫入10個5到txt檔
這5個function我將他們給work thread執行
而這5個work thread則給視窗上一個按鈕觸發
意即按了那個按鈕 就會執行將檔案寫入選定txt檔的動作
希望得到的正確結果:
txt檔裡面的寫入資料只能有一組pattern
即1111111111 or 2222222222 or 333333333 or 444444444 or 5555555555
程式跑出來的錯誤結果:
程式跑出來 txt檔卻是(不一定按照以下順序 但是必定有5組)
111111111122222222223333333334444444445555555555
開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
vc++ 使用vc6
有問題的code: (請善用置底文標色功能)
void CTest1117Dlg::OnWrite()
{
int i=1;
theApp.m_pThreads[0]=AfxBeginThread(WorkerThreadFunction_1,(LPVOID)i);
Sleep(100);
i=2;
theApp.m_pThreads[1]=AfxBeginThread(WorkerThreadFunction_2,(LPVOID)i);
Sleep(100);
i=3;
theApp.m_pThreads[2]=AfxBeginThread(WorkerThreadFunction_3,(LPVOID)i);
Sleep(100);
i=4;
theApp.m_pThreads[3]=AfxBeginThread(WorkerThreadFunction_4,(LPVOID)i);
Sleep(100);
i=5;
theApp.m_pThreads[4]=AfxBeginThread(WorkerThreadFunction_5,(LPVOID)i);
Sleep(100);
}
補充說明:
補充WorkerThreadFunction_1的定義
///////////////////////////////////////////
UINT CTest1117Dlg::WorkerThreadFunction_1(LPVOID pParam)
///////////////////////////////////////////
{
CFile file;
CCriticalSection cs;
cs.Lock();
file.Open(dpath,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);
CString strValue ;
for(int i=1;i<100;i++)
{
file.SeekToEnd(); //將指標移至文件末尾進行追加
strValue="1";
file.Write(strValue,strValue.GetLength());
}
//關閉文件
file.Close();
cs.Unlock();
return 0;
}
懇請版上朋友不吝指教小弟錯誤的地方 謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.160.146.250
推
11/22 22:09, , 1F
11/22 22:09, 1F
→
11/22 22:09, , 2F
11/22 22:09, 2F
推
11/22 22:10, , 3F
11/22 22:10, 3F
抱歉 會問這個問題是因為上級要我了解執行緒的道理
要我寫5個執行緒去看txt檔寫入的資訊
他們有跟我說答案是1-5其中一組 而不會是從1排到5
謝謝各位
※ 編輯: slimbody15 來自: 1.160.146.250 (11/22 22:12)
→
11/22 22:11, , 4F
11/22 22:11, 4F
→
11/22 22:14, , 5F
11/22 22:14, 5F
→
11/22 22:15, , 6F
11/22 22:15, 6F
→
11/22 22:15, , 7F
11/22 22:15, 7F
推
11/22 22:20, , 8F
11/22 22:20, 8F
→
11/22 22:21, , 9F
11/22 22:21, 9F
→
11/22 22:22, , 10F
11/22 22:22, 10F
→
11/22 22:23, , 11F
11/22 22:23, 11F
推
11/22 22:24, , 12F
11/22 22:24, 12F
推
11/22 22:25, , 13F
11/22 22:25, 13F
→
11/22 22:25, , 14F
11/22 22:25, 14F
→
11/22 22:25, , 15F
11/22 22:25, 15F
→
11/22 22:26, , 16F
11/22 22:26, 16F
→
11/22 22:27, , 17F
11/22 22:27, 17F
→
11/22 22:27, , 18F
11/22 22:27, 18F
→
11/22 22:27, , 19F
11/22 22:27, 19F
→
11/22 22:29, , 20F
11/22 22:29, 20F
推
11/22 22:32, , 21F
11/22 22:32, 21F
推
11/22 22:34, , 22F
11/22 22:34, 22F
→
11/22 22:36, , 23F
11/22 22:36, 23F
→
11/23 08:46, , 24F
11/23 08:46, 24F
討論串 (同標題文章)