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