编程怎么做暂停程序

时间:2025-01-29 15:49:30 单机游戏

在不同的编程语言中,有多种方法可以实现程序的暂停。以下是一些常见的方法:

使用time模块的sleep函数

Python:

```python

import time

print("程序开始,正在暂停...")

time.sleep(5) 暂停5秒

print("暂停结束,程序继续执行。")

```

C语言:

```c

include

include

int main() {

printf("程序开始执行\n");

sleep(5); // 暂停5秒

printf("程序继续执行\n");

return 0;

}

```

C++:

```cpp

include

include

int main() {

std::cout << "程序开始执行" << std::endl;

std::this_thread::sleep_for(std::chrono::seconds(5)); // 暂停5秒

std::cout << "程序继续执行" << std::endl;

return 0;

}

```

使用input函数

Python:

```python

print("按任意键继续...")

input() 等待用户输入

print("继续执行。")

```

C语言:

```c

include

int main() {

printf("按任意键继续...\n");

getchar(); // 等待用户输入

printf("继续执行。\n");

return 0;

}

```

C++:

```cpp

include

int main() {

std::cout << "按任意键继续...\n";

std::cin.get(); // 等待用户输入

std::cout << "继续执行。" << std::endl;

return 0;

}

```

使用条件变量(适用于多线程编程):

C++:

```cpp

include

include

include

include

std::mutex mtx;

std::condition_variable cv;

bool ready = false;

void print_id(int id) {

std::unique_lock lck(mtx);

while (!ready) { // 如果ready为false,则等待

cv.wait(lck);

}

std::cout << "thread " << id << '\n';

}

int main() {

std::thread threads;

// spawn 10 threads:

for (int i = 0; i < 10; ++i)

threads[i] = std::thread(print_id, i);

std::this_thread::sleep_for(std::chrono::seconds(1));

{

std::unique_lock lck(mtx);

ready = true; // set the ready flag to true

}

cv.notify_all(); // notify all threads

for (auto &th : threads) th.join();

return 0;

}

```

使用信号量(适用于多线程编程):

C++: