写一个mutex 的Cpp例子
时间: 2023-05-12 19:07:18 浏览: 66
好的,以下是一个简单的mutex的Cpp例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建一个mutex对象
void print_block(int n, char c) {
// 使用lock_guard保护共享资源
std::lock_guard<std::mutex> lock(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main() {
std::thread t1(print_block, 50, '*');
std::thread t2(print_block, 50, '#');
t1.join();
t2.join();
return 0;
}
```
这个例子中,我们使用了C++11中的mutex和lock_guard来保护共享资源,避免了多个线程同时访问导致的数据竞争问题。在print_block函数中,我们使用lock_guard对mutex进行加锁,保证了在执行print_block函数期间,其他线程无法访问共享资源。
相关问题
能帮我写一个基于CPP11的线程池吗
当然可以,下面是一个基于C++11的线程池示例:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; i++) {
threads.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& thread : threads) {
thread.join();
}
}
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task] { (*task)(); });
}
condition.notify_one();
return res;
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
```
在这个线程池中,我们使用了C++11的新特性`std::thread`、`std::mutex`、`std::condition_variable`等来实现线程池的基本功能。同时,我们也使用了C++11的新特性`std::future`和`std::packaged_task`来实现任务的异步执行和结果的获取。
使用时,可以通过以下方式来创建一个线程池,并提交任务:
```cpp
ThreadPool pool(4);
auto result = pool.enqueue([](int answer) { return answer; }, 42);
std::cout << "result: " << result.get() << std::endl;
```
这个例子中,我们创建了一个拥有4个线程的线程池,并提交了一个lambda表达式作为任务,lambda表达式接受一个int类型的参数,返回一个int类型的结果。我们通过`result.get()`来获取任务的执行结果。
当然,在实际使用中,我们可以通过`enqueue`函数提交不同类型的任务,只要任务符合函数的参数和返回值类型即可。同时,我们也可以通过控制线程池中线程的数量来更好地控制程序的性能。
写一个线程锁的完整调用例子
当创建并启动多个线程访问共享资源时,使用互斥锁可以确保线程之间的互斥访问。以下是一个完整的使用线程锁的例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义互斥锁
int sharedData = 0; // 共享资源
// 线程函数,用于递增共享资源的值
void incrementData() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // 锁住互斥锁
sharedData++; // 对共享资源进行操作
}
}
int main() {
std::thread t1(incrementData);
std::thread t2(incrementData);
t1.join();
t2.join();
std::cout << "Shared data: " << sharedData << std::endl;
return 0;
}
```
在上述示例中,我们创建了一个互斥锁`mtx`和一个共享资源`sharedData`。`incrementData`函数用于递增`sharedData`的值,它会通过互斥锁确保每个线程在访问共享资源时是互斥的。在主函数中,我们创建了两个线程`t1`和`t2`,并启动它们来同时递增`sharedData`的值。最后,我们输出最终的共享数据值。
通过使用互斥锁,我们可以确保在每个线程访问共享资源时,只有一个线程能够持有互斥锁并执行操作,从而避免了数据竞争和不一致的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)