21xrx.com
2024-06-03 01:15:53 Monday
登录
文章检索 我的文章 写文章
C++等待函数介绍与使用方法
2023-07-02 22:31:59 深夜i     --     --
C++等待函数 等待函数介绍 使用方法 延时 同步等待

在C++编程中,经常需要使用等待函数来实现线程等待或延时等应用。本文将介绍C++中常用的等待函数,以及如何使用它们。

一、sleep()函数

sleep()函数可以用来使程序暂停一段时间。它的原型如下:

void sleep(int seconds);

其中参数seconds表示程序暂停的秒数。

示例代码:

#include

#include

using namespace std;

int main()

{

  cout << "开始睡眠" << endl;

  sleep(3);

  cout << "睡眠结束" << endl;

  return 0;

}

运行结果:

开始睡眠

睡眠结束

在上述示例代码中,程序执行到sleep(3)时,会暂停3秒钟。可以根据实际需要调整sleep()函数中的参数。

二、usleep()函数

usleep()函数可以用来实现毫秒级别的时间延迟。它的原型如下:

int usleep(useconds_t usec);

其中参数usec表示程序暂停的微秒数。

示例代码:

#include

#include

using namespace std;

int main()

{

  cout << "开始睡眠" << endl;

  usleep(3000);

  cout << "睡眠结束" << endl;

  return 0;

}

运行结果:

开始睡眠

睡眠结束

在上述示例代码中,程序执行到usleep(3000)时,会暂停3毫秒。

三、wait()函数

wait()函数可以用来等待子进程结束后再继续进行。它的原型如下:

pid_t wait(int *status);

其中参数status用于获取子进程的结束状态码。

示例代码:

#include

#include

#include

using namespace std;

int main()

{

  pid_t pid = fork();

  if(pid == 0)

  {

    cout << "子进程启动" << endl;

    sleep(3);

    cout << "子进程结束" << endl;

    exit(0);

  }

  else if(pid > 0)

  {

    cout << "父进程等待子进程结束" << endl;

    int status;

    wait(&status);

    cout << "子进程结束状态码:" << status << endl;

  }

  else

    cout << "子进程创建失败" << endl;

  return 0;

}

运行结果:

父进程等待子进程结束

子进程启动

子进程结束

子进程结束状态码:0

在上述示例代码中,父进程创建了一个子进程,在子进程中暂停3秒后结束。而父进程通过wait()函数等待子进程结束后再继续执行。

总结:

本文介绍了C++中常用的等待函数sleep()、usleep()和wait()的使用方法。在实际编程中,可以根据需要选择合适的等待函数来实现线程等待、延时等应用。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复