gpt4 book ai didi

c++ - 线程同步问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:20 34 4
gpt4 key购买 nike

我接到了一项任务,即通过 Linux 上的 C/C++ 线程(使用一些遗留代码)单独复制数百万个文件夹。

扫描文件夹、将文件从源文件夹复制到目标文件夹等个别功能已经到位,并且在串行执行时可以正常工作。当通过线程完成时,整个问题就出现了。

问题:代码每次执行时的行为都略有不同。有时它会正确复制整个文件夹列表,但有时会失败。

示例失败输出是:

foldername is [Junk] tCount is 2 cntr is 3

val of folder is Junk tid is 3055356816

foldername is [Notes] tCount is 3 cntr is 4

val of folder is tid is 3042966416

Folder creation failed /var/anshul/work/copyDirectoryThreaded/test_copied/email/

在函数线程中,传递的参数值变为NULL。在上面的例子中,参数 Notes 是从 main 函数传递给线程函数的,但是在线程函数中,接收到的值是 NULL

我的主要代码如下所示:

int main()
{
int cntr=0;
int Val = 3;

tCount = 0;
pthread_t thread[folderCount]; // folderCount is total number of folders scanned
int iret[folderCount];
std::map<std::string,int>::iterator mFolderIt; // mFolder map contains the folder list.
char foldername[30] = {0};

for ( mFolderIt=mFolder.begin() ; mFolderIt != mFolder.end(); )
{
if(tCount < Val)
{
pthread_mutex_lock( &mutex_tCount );
tCount++;
pthread_mutex_unlock( &mutex_tCount );

sprintf(foldername,"%s",(*mFolderIt).first.c_str() );
fprintf(stderr, "foldername is [%s] tCount is %d cntr is %d\n",foldername,tCount,cntr);
iret[cntr] = pthread_create( &thread[cntr], NULL,folderCopy , (void*)foldername);
cntr++;
usleep(1); // most crucial for threading.......
mFolderIt++;
memset(foldername,0,30);
}
else
{
while(tCount >= Val)
{
usleep(10);
}
}
}

for(int x = 0 ; x<folderCount ;x++)
pthread_join(thread[x],NULL);

return 1;
}

线程函数代码:

void * folderCopy(void *f)
{
fprintf(stderr,"val of folder is %s tid is %u\n", folder, (unsigned int)pthread_self());

pthread_mutex_lock( &mutex_tCount );
tCount--;
pthread_mutex_unlock( &mutex_tCount );
pthread_exit(NULL);
return NULL;
}

谁能帮我解决这个问题。

最佳答案

                    fprintf(stderr, "foldername is [%s] tCount is %d cntr is %d\n",foldername,tCount,cntr);
iret[cntr] = pthread_create( &thread[cntr], NULL,folderCopy , (void*)foldername);
cntr++;
usleep(1); // most crucial for threading.......
mFolderIt++;
memset(foldername,0,30);

不能保证 usleep 有足够的时间。相反,您应该绝对确定内存将保持有效,直到另一个线程有机会使用它。最简单的方法是给另一个线程它自己的数据拷贝:

iret[cntr] = pthread_create(&thread[cntr], NULL, folderCopy, strdup(foldername));
// ...

void * folderCopy(void *f)
{
char *folderName = (char *)f;
// do something with folderName
free(f);
return NULL;
}

还有其他方法可以确保线程已获取数据拷贝,但这是最简单的方法。

关于c++ - 线程同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146648/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com