我正在构建一个系统,其中多个从属进程通过unix域套接字进行通信,并且它们同时写入同一文件.我从未研究过文件系统或这个特定的文件系统(ext4),但感觉这里可能存在一些危险.
每个进程写入输出文件的不相交子集(即,正在写入的块中没有重叠).例如,P1
仅写入文件的前50%,P2
仅写入第二个50%.或者P1
在P2
写入偶数块时可能只写入奇数块.
拥有P1
和P2
(在不同的线程上同时运行)写入同一文件而不使用任何锁定是否安全?换句话说,文件系统是否隐式强加了某种锁定?
注意:遗憾的是,我不能随意输出多个文件并在以后加入.
注意:自发布此问题以来,我的阅读与下面仅发布的答案不一致.我读过的所有内容都表明我想做的事情很好,而下面的受访者坚持认为我所做的是不安全的,但我无法辨别所描述的危险.
public class RefMix {
public static void main(String[] args) {
Object[] a = {null, "foo"};
Object[] b = {"bar", b};
a[0] = b;
System.out.println(a[0][0]);
}
}
Run Code Online (Sandbox Code Playgroud)
我的理解是数组是Java中的对象,因此是Object类型的子类.我的进一步理解是,2-dim数组被实现为对数组的引用数组.因此我不明白为什么我的a [0] [0] bar
在上面的代码中没有产生.相反它不编译:
RefMix.java:7: array required, but java.lang.Object found
Run Code Online (Sandbox Code Playgroud) 如果我遇到feof()
然后stat
显示文件已经增长,有没有办法读取添加的数据而不执行fclose()
和fopen()
?
我从学生那里得到了这个代码,由于涉及x++
和的竞争条件,它无法正常工作x--
.他补充synchronized
到run()
方法试图摆脱这个错误,但显然这只是排除线程进入run()
了对同一对象(这是从来没有摆在首位的问题),但并不妨碍独立的对象修改同一静态变量x
在同一时间.
public class DataRace implements Runnable {
static volatile int x;
public synchronized void run() {
for (int i = 0; i < 10000; i++) {
x++;
x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; …
Run Code Online (Sandbox Code Playgroud) 我正在关注Twisted教程,并尝试了该文章中的以下代码:
# Read username, output from non-empty factory, drop connections
from twisted.internet import protocol, reactor
from twisted.protocols import basic
class FingerProtocol(basic.LineReceiver):
def lineReceived(self, user):
self.transport.write(self.factory.getUser(user)+"\r\n")
self.transport.loseConnection()
class FingerFactory(protocol.ServerFactory):
protocol = FingerProtocol
def __init__(self, **kwargs):
self.users = kwargs
def getUser(self, user):
return self.users.get(user, "No such user")
reactor.listenTCP(1079, FingerFactory(moshez='Happy and well'))
reactor.run()
Run Code Online (Sandbox Code Playgroud)
我尝试了nc localhost 1079
它只是挂起:没有回复.但后来telnet localhost 1079
工作得很好.为什么?
public static void main(String args[]) throws Exception {
ConcurrentHashMap<byte[], Integer> dps =
new ConcurrentHashMap<byte[], Integer>();
System.out.println(dps.putIfAbsent("hi".getBytes(), 1));
System.out.println(dps.putIfAbsent("hi".getBytes(), 1));
}
Run Code Online (Sandbox Code Playgroud)
版画
null
null
Run Code Online (Sandbox Code Playgroud)
为什么不在1
第二行打印?我已经阅读了语义putIfAbsent
,它应该保证工作.(注意:这是从大型并发程序中提炼出来的......正如您所看到的,它现在是单线程的.)