multithreading - bash:写入命名管道是原子的吗?

标签 multithreading bash named-pipes

我正在尝试使用 bash 并行处理文件集。我正在使用命名管道来保持进程数量固定并收集进程的输出。

我假设对命名管道的写入是原子的,即不同进程的输出不会混淆。这是一个安全的假设吗?

非常感谢任何建议。我仅限于使用 bash。

代码如下:

mytask()
{
  wItem=$1
  #dummy func; process workItem
  rt=$RANDOM
  st=$rt;
  let "rt %= 2"
  let "st %= 10"
  sleep $st
  return $rt
}

parallelizeTask()
{
workList=$1
threadCnt=$2
task=$3
threadSyncPipeD=$4
outputSyncPipeD=$5

ti=0
for workItem in $workList; do
  if [ $ti -lt $threadCnt ]; then
    { $task $workItem; if [ $? == 0 ]; then result="success"; else result="failure"; fi; \
      echo "$result:$workItem" >&$outputSyncPipeD; echo "$result:$workItem" >&$threadSyncPipeD; } &
    ((ti++))
    continue;
  fi
  while read n; do
      ((ti--))
      break;
  done <&$threadSyncPipeD
  { $task $workItem; if [ $? == 0 ]; then result="success"; else result="failure"; fi; \
    echo "$result:$workItem" >&$outputSyncPipeD; echo "$result:$workItem" >&$threadSyncPipeD;} &
  ((i++))
done
wait
echo "quit" >&$outputSyncPipeD

while read n; do
 if [[ $n == "quit" ]]; then
    break;
 else
    eval $6="\${$6}\ \$n"
 fi
 done <&$outputSyncPipeD;
}

main()
{
  if [ ! -p threadSyncPipe ]; then
     mkfifo threadSyncPipe
   fi

   if [ ! -p outputSyncPipe ]; then
      mkfifo outputSyncPipe
   fi

   exec 4<>threadSyncPipe
   exec 3<>outputSyncPipe
   gout=
   parallelizeTask "f1 f2 f3 f4 f5 f6" 2 mytask 3 4 gout

   echo "finalOutput: $gout";
   for f in $gout; do
       echo $f
   done

   rm outputSyncPipe
   rm threadSyncPipe
}

main

我在下面找到了相关帖子,其中包含我的问题的答案。我修改了标题以使其更合适。

Are there repercussions to having many processes write to a single reader on a named pipe in posix?

最佳答案

我在下面给出的相关帖子中找到了答案,根据它,只要写入消息小于页面大小 4k(页面大小取决于系统配置),对 fifo 的写入就是原子的。

Are there repercussions to having many processes write to a single reader on a named pipe in posix?

谢谢大家的回复和建议。

关于multithreading - bash:写入命名管道是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575726/

相关文章:

c++ - 无法将接口(interface)从主线程编码到工作线程

linux - 删除目录中除列表中提到的文件之外的所有文件

c# - NamedPipeServerStream 和 WaitForConnection 方法

c# - C# 和 C++ 之间可以传输什么类型的数据

java - 多线程写入文件时使用BufferReader读取文件

C++11线程等待

bash - 在 shell 中使用 seq 的数字序列的长度

Bash:在 X 列中保留所有具有重复值的行

c# - ffmpeg 输出管道到命名的 Windows 管道

c++ - Qt C++ - 多线程视频帧转换