线程同步问题
Thread synchronization issue
我被赋予了一项任务,即在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
是从主函数传递到线程函数的,但在线程函数中,接收到的值是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 %dn",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 %un", 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 %dn",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;
}
还有其他方法可以确保线程获取了数据的副本,但这是最简单的方法。
作为第四个参数传递的指针不是线程安全的。
pthread_create( &thread[cntr], NULL,folderCopy , (void*)foldername);
因此,每个线程都接收到相同的指针,并且由于主线程正在覆盖该指针的内容,因此无法知道任何特定线程看到的内容。
您需要为每个线程制作一个内容的私有副本(然后让线程清理它)。
相关文章:
- 线程过程中的线程同步问题
- 使用 qt 和 opengl、定时精度和垂直同步问题、c++ 显示图像
- C++11 中 3 个线程和 2 个共享资源的同步问题
- 队列的同步问题
- C++ 获取同步密钥状态状态问题
- Google 日历与订阅日历"Remember the milk"同步问题
- Qt QState机器同步问题:初始状态未在启动信号上设置
- POSIX线程同步和/或pthread_create()参数传递问题
- 线程同步问题
- MP3帧头检测FFF/FFE同步问题
- 线程同步问题
- 在同步问题中,弱指针可以代替互斥锁或临界区吗?
- 与MPI-2单向通信同步单个int值的问题
- 同步MPI-2单向通信中的顺序问题
- QStateMachine的同步问题
- c++并发、同步设计,避免多次执行问题
- 录制视频和音频-同步问题
- Poco 线程同步问题
- Boost Asio:关于教程的一些问题(同步日间服务器/客户端)
- Turbo c++文件同步问题