To launch a new thread to perform a task in C++11, one can make use of the standard thread library. The following code shows how to create a thread and execute a set of instructions:
void aFunction(int maxNum) {
std::vector<int> nums;
nums.reserve(maxNum);
int sum = 0;
for (int i = 0; i < maxNum; ++i) {
nums[i] = rand() % maxNum;
sum += nums[i];
}
float average = sum / static_cast(maxNum);
std::cout << "The average is: " << average << std::endl;
}
int main(int argc, const char * argv[]) {
// create a new thread and start execution of aFunction with argument maxNum
int maxNum = 100;
std::thread thread1(aFunction, maxNum);
// wait for a thread to finish execution
thread1.join();
return 0;
}
