2012-05-04 36 views
-1

我从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; 
} 

我无法发布整个代码作为其基准代码,并且非常长且详细。 请帮忙。

+2

有数以百计的方法来启动线程和传递参数。你使用了哪一个? – PlasmaHH

+0

这个变量是否标记为volatile? –

+1

请告诉我们代码。 – Romain

回答

0

如果我理解正确的问题,你要调用从一个线程的成员函数,你可以,如果你有C++ 11

std::thread th(&my_class::my_mem_func, &my_object); 

这将创建一个线程th和执行的my_mem_func只是做my_object

编辑

std::thread th(&my_writer::write_some, &writer_object, data); 
th.join(); 
+0

感谢您的回复。 其实,我使用pthread_create()API来创建一个线程。我传递下面的函数作为开始例程给线程其通过在pthread_create()创建 的extern “C” { 无效*运行(无效* ARG) { CFileOp *反式=的static_cast (ARG); trans-> write_block(arg); return 0; } } run()然后调用属于某个其他类的write_block()方法。 问题是线程能够到达write_block()方法,但无法访问该类的成员变量的值。 请帮忙 – sam32

+0

@ sam32你将不得不张贴代码,你必须使用pthreads,std :: threads符合标准和跨平台,我不能真正帮助你使用pthreads。无论哪种方式,我们仍然需要看到一个CONCISE代码示例/ – 111111

+0

我已经在我的帖子中发布了一些相关的代码 – sam32

相关问题