and*_*pcg 1 c time posix fork core
我正在编写一个程序,它使用cpu power来处理一些信息.该程序取决于CPU核心.如果有2个内核,程序将fork()两次以创建2个工作实例并返回结果.
#define CORES 4
void worker(int id)
{
// blablabla work here
printf("worker %d\n",id);
printf("[%d] I'm child of %d\n",getpid(),getppid());
}
int main (int argc, const char * argv[])
{
int pid;
for (int i=0; i<CORES; i++)
{
pid = fork();
if (pid == 0) // if child
{
worker(i);
exit(0);
}
else if (pid>0)
{
printf("[%d] Big father here!\n",getpid());
}
else
{
printf("--- Fork problem ---");
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
使用wait()等待孩子结束:
int status;
pid_t pid;
while ((pid = wait(&status)) != -1) {
// pid just terminated
}
// all children terminated
Run Code Online (Sandbox Code Playgroud)
有关测量时间的信息,请参阅gettimeofday():
struct timeval tv = {0};
gettimeofday(&tv, NULL);
Run Code Online (Sandbox Code Playgroud)
struct timeval:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
Run Code Online (Sandbox Code Playgroud)