为什么这些并行过程的输出没有搞砸?
Why is the output from these parallel processes not messed up?
一切都在完美执行。
words.dict 文件每行包含一个单词:
$ cat words.dict
cat
car
house
train
sun
today
station
kilometer
house
away
chapter.txt 文件包含纯文本:
$ cat chapter.txt
The cars are very noisy today.
The train station is one kilometer away from his house.
下面的脚本在 result.txt 文件中添加了 words.dict 中所有在 chapter.txt 文件中使用 grep 命令找不到的单词,使用 10 个并行grep:
$ cat psearch.sh
#!/bin/bash --
> result.txt
max_parallel_p=10
while read line ; do
while [ $(jobs | wc -l) -gt "$max_parallel_p" ]; do sleep 1; done
fgrep -q "$line" chapter.txt || printf "%s\n" "$line" >> result.txt &
done < words.dict
wait
一个测试:
$ ./psearch.sh
$ cat result.txt
cat
sun
我认为测试会在 result.txt
中生成混合词
csat
un
但这似乎真的有效。
请看一下并解释为什么?
后台作业不是线程。使用多线程进程,您可以获得这种效果。原因是每个进程只有一个标准输出流(stdout)。在多线程程序中,所有线程共享相同的输出流,因此对 stdout 的不受保护的写入可能会导致如您所述的乱码输出。但是你没有多线程程序。
当您使用 &
限定符时 bash 创建一个新的子进程,它有自己的 stdout 流。通常(取决于实现细节)这是在换行符上刷新的。因此,即使文件可能被共享,粒度也是按行划分的。
两个进程可以完全同时刷新到文件的可能性很小,但是您的代码具有子进程和睡眠,因此不太可能。
您可以尝试从 printf
中取出换行符,但考虑到其余代码的低效率和小数据集,它仍然不太可能。很可能每个过程都在下一个过程开始之前完成。
一切都在完美执行。
words.dict 文件每行包含一个单词:
$ cat words.dict
cat
car
house
train
sun
today
station
kilometer
house
away
chapter.txt 文件包含纯文本:
$ cat chapter.txt
The cars are very noisy today.
The train station is one kilometer away from his house.
下面的脚本在 result.txt 文件中添加了 words.dict 中所有在 chapter.txt 文件中使用 grep 命令找不到的单词,使用 10 个并行grep:
$ cat psearch.sh
#!/bin/bash --
> result.txt
max_parallel_p=10
while read line ; do
while [ $(jobs | wc -l) -gt "$max_parallel_p" ]; do sleep 1; done
fgrep -q "$line" chapter.txt || printf "%s\n" "$line" >> result.txt &
done < words.dict
wait
一个测试:
$ ./psearch.sh
$ cat result.txt
cat
sun
我认为测试会在 result.txt
中生成混合词csat
un
但这似乎真的有效。
请看一下并解释为什么?
后台作业不是线程。使用多线程进程,您可以获得这种效果。原因是每个进程只有一个标准输出流(stdout)。在多线程程序中,所有线程共享相同的输出流,因此对 stdout 的不受保护的写入可能会导致如您所述的乱码输出。但是你没有多线程程序。
当您使用 &
限定符时 bash 创建一个新的子进程,它有自己的 stdout 流。通常(取决于实现细节)这是在换行符上刷新的。因此,即使文件可能被共享,粒度也是按行划分的。
两个进程可以完全同时刷新到文件的可能性很小,但是您的代码具有子进程和睡眠,因此不太可能。
您可以尝试从 printf
中取出换行符,但考虑到其余代码的低效率和小数据集,它仍然不太可能。很可能每个过程都在下一个过程开始之前完成。