使用threadpool模块多线程写同一个文件的时,需要加锁吗

使用threadpool模块多线程写同一个文件的时,需要加锁吗,第1张

当然需要加锁线程池本身是不关心临界问题的。多线程写同一个文件如果不加锁,会出现写入数据交错的情况。

任何线程池模型都不会内置临界保护机制,因为不同业务场景下临界保护的方式很多,对性能影响很大,所以需要自己手动去做。

Java中不同的线程是可以同时 *** 作一个文件的,只不过有时候因为进程执行的快慢,会出现数据读取不同步的问题,例子如下:Public class Readfile implements Runnable{ public void run(){ FileInputStream inputStream = new FileInputStream(file)//读数据 byte[] buffer = new byte[1024] int size while ((size = inputStream.read(buffer)) >0) { outputStream.write(buffer, 0, size)//写数据 } inputStream.close()// outputStream.close()} public satatic void main(String args []) throws InterruptedException{ Readfile rf = new Readfile() Thread t1 = new Thread(rf)//开启一个线程 Thread t2 = new Thread(rf)//开启第二个线程 t1.start() t2.start()}}

#include <io.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/locking.h>

#include <share.h>

#include <fcntl.h>

#include <stdio.h>

#include <stdlib.h>

void main( void )

{

   int  fh, numread

   char buffer[40]

   /* Quit if can't open file or system doesn't 

    * support sharing. 

    */

   fh = _sopen( "locking.c", _O_RDWR, _SH_DENYNO, 

                 _S_IREAD | _S_IWRITE )

   if( fh == -1 )

      exit( 1 )

   /* Lock some bytes and read them. Then unlock. */

   if( _locking( fh, LK_NBLCK, 30L ) != -1 )

   {

      printf( "No one can change these bytes while I'm reading them\n" )

      numread = _read( fh, buffer, 30 )

      printf( "%d bytes read: %.30s\n", numread, buffer )

      lseek( fh, 0L, SEEK_SET )

     _locking( fh, LK_UNLCK, 30L )

      printf( "Now I'm done. Do what you will with them\n" )

   }

   else

      perror( "Locking failed\n" )

   _close( fh )

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/6075605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-13
下一篇 2023-03-13

发表评论

登录后才能评论

评论列表(0条)

保存