描述:
* 1. 采用C语言, 多线程 对同一个文件进行写操作;
* 2.每个线程有自己的写入位置;
* 3.每个线程有自己的数据缓冲区;
* 4.写文件前, 会 加锁(全局变量), 然后 将文件句柄 跳跃到指定位置, 写下线程缓冲区的数据;
* 5.现象: 写的是图片, 经常出现写入数据出错, 图片打不开;
* 6.日志: 对写文件前后的 文件句柄进行位置打印, 位置正确.
(每个线程进行写文件的)代码实现: 各线程都会打开同一个文件获取句柄,
void write_file(FILE* fp, char *srcContent, int Lenth, int index)
{
int nwrite = 0, len = 0;
pthread_mutex_lock(&g_muetx_lock);
printf("---------- 1 -----------\n");
if((fseek(fp, threadWorkHandle[index].writeInitPosition , SEEK_SET)) == -1)
{
myprint("Err : func lseek()");
assert(0);
}
myprint("pthread : %d, The write begin current : %lu, fp : %p", index, ftell(fp), fp);
while(nwrite < Lenth)
{
if((len = fwrite( srcContent + nwrite, 1, Lenth - nwrite, fp)) < 0)
{
myprint("Err : func fwrite()");
assert(0);
}
nwrite += len;
}
threadWorkHandle[index].writeInitPosition += Lenth;
myprint("pthread : %d, The write end : %lu, nwrite : %d", index, ftell(fp), nwrite);
//fflush(fp);
printf("---------- 2 -----------\n");
pthread_mutex_unlock(&g_muetx_lock);
}