admin 管理员组

文章数量: 1184232


2024年3月29日发(作者:开场视频素材免费)

c++多线程实现方式

多线程在现代编程中越来越重要。C++是一种支持多线程编程的

高级编程语言,并且提供了多种实现方式。在本文中,我们将讨论

C++中多线程的实现方式。

1. 使用C++11提供的std::thread类

C++11提供了std::thread类,使得多线程编程变得更加简单。

这个类的使用非常类似于Java中的Thread类。我们可以使用以下代

码来创建和启动一个新线程:

```

#include

#include

void func()

{

std::cout << 'New thread started' << std::endl;

}

int main()

{

std::thread t(func);

();

return 0;

}

```

- 1 -

上面的代码创建了一个新线程,并通过调用std::thread的

join()方法等待线程完成执行。当线程执行完成后,程序将继续执行。

2. 使用C++11提供的std::async函数

C++11提供了std::async函数,可以在单独的线程中异步执行

指定的函数。这个函数的返回值是std::future,我们可以使用get

方法获取函数执行的结果。

```

#include

#include

int func()

{

std::cout << 'New thread started' << std::endl;

return 42;

}

int main()

{

std::future result = std::async(std::launch::async,

func);

std::cout << 'Waiting ' << std::endl;

int res = ();

std::cout << 'Result is ' << res << std::endl;

return 0;

- 2 -

}

```

上面的代码创建了一个新线程,并异步执行了func函数。我们

使用std::future获取函数执行的结果,并在主线程中输出结果。

3. 使用C++11提供的互斥锁

多线程程序中访问共享资源时需要使用互斥锁,以避免多个线程

同时修改同一个资源。C++11提供了std::mutex类来实现互斥锁。

```

#include

#include

#include

std::mutex mtx;

void func()

{

std::lock_guard lock(mtx);

std::cout << 'New thread started' << std::endl;

}

int main()

{

std::thread t(func);

();

return 0;

- 3 -

}

```

上面的代码创建了一个互斥锁,并在func函数中使用

std::lock_guard保护共享资源。这样就可以确保同一时间只有一个

线程可以访问共享资源,避免了数据竞争的问题。

总结

在本文中,我们讨论了C++中多线程的实现方式。C++11提供了

std::thread类、std::async函数和std::mutex类来简化多线程编

程。使用这些工具,我们可以轻松地编写高效的多线程应用程序。

- 4 -


本文标签: 执行 线程 函数 使用 资源