Reputation: 57
I have a client use a bufferedwriter for write in a socket. But client create a thread that can use the same bufferedwriter. I don't use lock for it and my program doesn't have problem, but have I a problem if the main thread of client and the thread of the client write in the bufferedwriter in the same time?
Upvotes: 1
Views: 208
Reputation: 409
Here is the answer of your question: How to get string between two characters using regular expression?
Use this:
$input = "hi my name [is] Mary [Poppins]";
$arr = explode(' ', $input);
$from = "[";
$to = "]";
function getStringBetween($input, $from, $to) {
$sub = substr($input, strpos($input, $from) + strlen($from), strlen($input));
return substr($sub, 0, strpos($sub, $to));
}
foreach ($arr as $data) {
echo getStringBetween($data, $from, $to) . " "; // is Poppins
}
Upvotes: 0
Reputation: 626
Writting to socket is not an atomic operation.
Is better to use a syncrhonized method to writting
Update
https://stackoverflow.com/a/1457347/5065312
All versions of Unix and Windows attempt to keep the write atomic, but apparently very few provide a guarantee.
And if you are using a Realtime Kernel the writes are not atomic.
Update 2:
IEEE Std 1003.1-2017 If the number bytes written to socket is not specified or if the number of bytes written to socket is more than {PIPE_BUF}, then, it does not guarantee that this writting is atomic.
For more information see: man 7 pipe
PostData: It is bad practice to write concurrently without controlling the flow. 99% can work because 99% of the time the socket output will be free
Upvotes: 1
Reputation: 311048
You will have to synchronize in the BufferedWriter
when writing from any thread. Even then you are going to have massive problems at the receiving end understanding the stream, unless your protocol consists merely of lines.
Upvotes: 0
Reputation: 140534
BufferedWriter
's documentation does not describe its thread safety; the package-level documentation says nothing either.
Even if the individual methods were implemented atomically, calling multiple methods on the writer would definitely not be atomic.
You should err on the side of caution and assume it is not thread-safe, and externally synchronize the instance. The fact that no bug has manifested yet does not imply the bug is absent.
Upvotes: 1