摘要:对于基于事件的程序,有一个限制。您不能充分利用多个内核来提高CPU利用率。即使您可以使用多线程编程来分配句柄,但每个循环仍然只有一个线程。此时,使用多个进程可以分担循环的压力,多进程+通信的方法比多线程+共享内存的方法更安全,更容易开发。#include<csdio>#include<studio。h˃ #include #我
对于基于事件(event-based)的程序来说, 有个限制,没办法很好地利用多核,提高CPU使用率.
即使能够使用多线程编程来分发 handle, 但是每个 loop 还是只有一个线程.
这时候, 使用多进程就能够分担 loop 的压力,并且通过多进程 + 通信的方法, 会比 多线程 + 共享内存的方法更加安全, 易于开发.
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <libuv/uv.h>
void on_exit(uv_process_t* req, int64_t exit_status, int term_signal) {
printf("exit_status = %lld , signal = %d
", exit_status, term_signal);
uv_close((uv_handle_t*)req, NULL);
}
int main() {
uv_loop_t* loop = uv_default_loop();
char* args[3];
args[0] = "mkdir";
args[1] = "test-dir";
args[2] = NULL;
uv_process_options_t options;
options.exit_cb = on_exit;
options.file = "mkdir";
//子进程就与父进程脱离了关系.
options.flags = UV_PROCESS_DETACHED;
options.args = args;
//创建子进程,子线程创建一个文件夹
int r;
uv_process_t child_req;
if ((r = uv_spawn(loop, &child_req, &options))) {
printf("%s
", uv_strerror(r));
return 1;
}
else {
printf(" child process ID = %d
", child_req.pid);
}
return uv_run(loop, UV_RUN_DEFAULT);
}