带for循环的多线程

带for循环的多线程

这是 bash 脚本代码的一部分我希望使用多线程

for DATABASE in $DATABASES ; do
    echo Converting $DATABASE
    # Check if the table is MyISAM (we don't want to convert InnoDB tables over and over again)
    TABLES=$(echo "SELECT TABLE_NAME FROM information_schema.TABLES where TABLE_SCHEMA = '$DATABASE' and ENGINE = 'MyISAM'" | $MYSQL_COMMAND)
    for TABLE in $TABLES ; do
        echo Converting MyISAM $TABLE to InnoDB
        echo "ALTER TABLE $TABLE ENGINE = INNODB" | $MYSQL_COMMAND $DATABASE
    done
    if [ "x$TABLES" = "x" ] ; then
        echo No MyISAM tables found in $DATABASE database
    fi
    echo
done

是否可以FOR使用多线程?

我正在考虑重写脚本并用xargs -P3 -n1 -I{}等等来做,但看起来肮脏的大部头书。

答案1

我做到了!

function convert_db() {
    echo Converting $1
    # Check if the table is MyISAM (we don't want to convert InnoDB tables over and over again)
    TABLES=$(echo "SELECT TABLE_NAME FROM information_schema.TABLES where TABLE_SCHEMA = '$1' and ENGINE = 'MyISAM'" | $MYSQL_COMMAND)
    for TABLE in $TABLES ; do
        echo Converting MyISAM $TABLE to InnoDB
        echo "ALTER TABLE $TABLE ENGINE = INNODB" | $MYSQL_COMMAND $1
    done
    if [ "x$TABLES" = "x" ] ; then
        echo No MyISAM tables found in $1 database
    fi
    echo
}

for DATABASE in $DATABASES ; do
convert_db $DATABASE &
done

相关内容