admin 管理员组

文章数量: 1087139


2024年3月29日发(作者:office怎么求平均分)

C++中可以使用多种方式来实现多线程,其中比较常用的有以下

几种:

1. 使用C++11标准库中的thread类

C++11标准库中提供了thread类,可以用来创建和管理线程。

下面是一个简单的例子:

```c++

#include

#include

void thread_function() {

std::cout << "Hello from thread!" << std::endl;

}

int main() {

std::thread t(thread_function); // 创建线程,并将函数

thread_function作为参数传递给线程t

(); // 等待线程t执行完毕

return 0;

}

```

2. 使用C++11标准库中的mutex和condition_variable类来实

现线程同步

多线程中经常需要多个线程之间共享数据,这时就需要使用线程

同步技术来保证数据的一致性和安全性。C++11标准库中提供

了mutex和condition_variable类来实现线程同步。下面是一个

简单的例子:

```c++

#include

#include

#include

#include

std::mutex mtx; // 全局互斥锁

std::condition_variable cv; // 全局条件变量

bool ready = false; // 全局标志位

void thread_function() {

std::unique_lock lock(mtx); // 加锁

(lock, []{return ready;}); // 等待标志位ready为true

std::cout << "Hello from thread!" << std::endl;

}

int main() {

std::thread t(thread_function); // 创建线程,并将函数

thread_function作为参数传递给线程t

std::this_thread::sleep_for(std::chrono::seconds(1)); // 主线

程休眠1秒钟,让子线程先执行

ready = true; // 设置标志位ready为true

_all(); // 通知所有等待在cv上的线程,标志位

ready为true了,可以继续执行了

(); // 等待线程t执行完毕

return 0;

}

```

3. 使用第三方库如或Pthreads库来实现多线程


本文标签: 线程 等待 全局 使用