php uniqid 高并发,PHP
以下是测试代码:
function new_child($func_name) {
$args = func_get_args();
unset($args[0]);
$pid = pcntl_fork();
if($pid == 0) {
function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);
} else if($pid == -1) {
echo "Couldn’t create child process.";
} else {
return $pid;
}
}
function generate() {
$t = array();
while($i ++ < 10) {
$uid = uniqid(true)."/n";
array_push($t, $uid);
}
sort($t);
while(-- $i >=0) {
echo array_shift($t);
}
}
while($i ++ < 1000) {
new_child(generate);
}
?>
测试方法: 命令行运行此程序,重定向输出到文件,然后利用下面程序检查重复:
$f = file("tttttt");
$f = array_count_values($f);
foreach($f as $k => $c) if($c > 1) echo $c.'_'.$k;
?>
解决方法: 我们现在是在uniqid后又加了rand(1, 10000),在1000并发,每进程10次uniqid的情况下,再没有产生重复。