是的,这当然是可能的。由于您不希望它们之间有任何干扰,因此请为它们提供唯一的数据以使用它们,这样您就不需要将对该数据的访问与 astd::mutex
或 make it同步std::atomic
。为了进一步减少线程之间的干扰,请根据std::hardware_破坏性_interference_size对齐数据。
您可以使用boost::thread::hardware_concurrency()来获取当前系统上可用的硬件线程数,这样您就不必对要运行的线程数进行硬编码。
可以使用传递对线程的引用std::ref
(否则线程将获得对数据副本的引用)。
在这里,我创建了一个std::list
线程和一个std::vector
数据来处理。
#include <cstdint> // std::int64_t
#include <iostream>
#include <list>
#include <new> // std::hardware_destructive_interference_size
#include <vector>
#include <boost/thread.hpp>
unsigned hardware_concurrency() {
unsigned rv = boost::thread::hardware_concurrency();
if(rv == 0) rv = 1; // fallback if hardware_concurrency returned 0
return rv;
}
// if you don't have hardware_destructive_interference_size, use something like this
// instead:
//struct alignas(64) data {
struct alignas(std::hardware_destructive_interference_size) data {
std::int64_t x;
};
void workerFunc(data& d) {
// work on the supplied data
for(int i = 0; i < 1024*1024-1; ++i) d.x -= i;
for(int i = 0; i < 1024*1024*1024-1; ++i) d.x += i;
}
int main() {
std::cout << "main: startup" << std::endl;
size_t number_of_threads = hardware_concurrency();
std::list<boost::thread> threads;
std::vector<data> dataset(number_of_threads);
// create the threads
for(size_t idx = 0; idx < number_of_threads; ++idx)
threads.emplace_back(workerFunc, std::ref(dataset[idx]));
std::cout << "main: waiting for threads" << std::endl;
// join all threads
for(auto& th : threads) th.join();
// display results
for(const data& d : dataset) std::cout << d.x << "\n";
std::cout << "main: done" << std::endl;
}
如果您使用的是 C++11(或更高版本),我建议您std::thread
改用。