我從main調用的某個函數產生線程。 此線程的啓動例程完全是另一個獨立類中的函數。所以要訪問這個類,我寫了一個extern「C」函數,通過它我可以調用啓動例程。 但問題是,在進入啓動例程後,線程無法訪問Class的構造函數設置的成員變量值。多線程 - 無法訪問由構造函數設置的類成員變量
這對我來說似乎很奇怪,因爲當我不使用線程運行代碼時,一切都很完美。 有人可以建議我會出什麼事嗎?
我張貼下面的一些相關的代碼細節:
'的extern 「C」{
void* run(void* arg)
{
CFileOp* trans = static_cast<CFileOp*>(arg);
trans->write_block(arg);
return 0;
}
}
int
TestFileOps(int file_size, CGlobalItems &globals){
...
for(i = 0; i < num_chunks; i++)
{
pthread_create(&thread_id[i], NULL, run, buf);
}
...
}`
//還有一類CFileOp其中有一些私有成員變量和write_block是它的一個公共函數。
void* CFileOp::write_block(PVOID buf)
{
int rc = my_write(78, buf, m_chunk_size);
if(rc != m_chunk_size)
{
fprintf(stderr, "Can't write block; rc=%d, buf=%p, chunk_size=%d\n", rc, buf, m_chunk_size);
pthread_exit((void *)-1);return 0;;
}
m_cur_pos++;
fprintf(stderr,"m_cur_pos: %d m_chunks_per_file: %d\t",m_cur_pos,m_chunks_per_file);
if(m_cur_pos >= m_chunks_per_file)
{
if(seek(0, SEEK_CUR) == -1)
pthread_exit((void *)-1);return 0;// return -1;
}
pthread_exit((void *)rc);
return 0;
}
我無法發佈整個代碼作爲其基準代碼,並且非常長且詳細。 請幫忙。
有數以百計的方法來啓動線程和傳遞參數。你使用了哪一個? – PlasmaHH
這個變量是否標記爲volatile? –
請告訴我們代碼。 – Romain