根据C++11标准编写一个将3个线程分配到3个CPU绑核并加锁的代码
时间: 2024-04-15 18:27:21 浏览: 26
在C++11标准中,可以使用`std::thread`来创建和管理线程,并使用`std::mutex`来实现互斥锁的功能。以下是一个使用C++11编写的将3个线程分配到3个CPU核心并加锁的示例代码:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <sched.h>
// 全局变量
int counter = 0;
std::mutex mtx;
// 线程函数
void thread_function(int thread_id) {
// 绑定线程到特定的CPU核心
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(thread_id, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
// 加锁
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Thread " << thread_id << ": Counter before increment: " << counter << std::endl;
counter++;
std::cout << "Thread " << thread_id << ": Counter after increment: " << counter << std::endl;
}
int main() {
std::vector<std::thread> threads;
// 创建线程
for (int i = 0; i < 3; i++) {
threads.emplace_back(thread_function, i);
}
// 等待线程完成
for (auto& thread : threads) {
thread.join();
}
return 0;
}
```
在这个示例代码中,我们使用了`std::thread`来创建线程,并将线程函数设置为`thread_function`。在`thread_function`中,我们首先设置线程的CPU亲和性,然后使用`std::lock_guard`来加锁,并对全局变量`counter`进行递增操作。
请注意,C++11中的`std::mutex`提供了互斥锁的功能,并且使用`std::lock_guard`可以方便地管理互斥锁的加锁和解锁操作。
编译时需要使用支持C++11标准的编译器,并链接pthread库。例如,使用以下命令编译代码:
```bash
g++ -std=c++11 -pthread main.cpp -o main
```
然后运行可执行文件:
```bash
./main
```
这样可以将3个线程分配到3个CPU核心并加锁进行操作。