how to declare a vector of thread - c++

i'm new in c++ programing and need some help to use a thread library with vector library...
first I follow this tutorial
but the compiler (visual studio 2013) show me errors and I don't know how correct it:
first declaration of function
void Fractal::calcIterThread(vector<vector<iterc>> &matriz, int desdePos, int hastaPos, int idThread){
...
}
in main loop
vector<vector<iterc>> res;
res.resize(altoPantalla);
for (int i = 0; i < altoPantalla; i++){
res[i].resize(anchoPantalla);
}
int numThreads = 10;
vector<thread> workers(numThreads);
for (int i = 0; i < numThreads; i++){ //here diferent try
thread workers[i] (calcIterThread, ref(res), inicio, fin, i)); // error: expresion must have a constant value
workers[i] = thread(calcIterThread, ref(res), inicio, fin, i)); // error: no instance of constructor "std::thread::thread" matches the argument list
}
...rest of code...
thanks for any help to clarify

Try this:
#include <functional>
#include <thread>
#include <vector>
// ...
int numThreads = 10;
std::vector<std::thread> workers;
for (int i = 0; i != numThreads; ++i)
{
workers.emplace_back(calcIterThread, std::ref(res), inicia, fin, i);
}
for (auto & t : workers)
{
t.join();
}

finally I can solve the problem with this change in my code...
workers.emplace_back(thread{ [&]() {
calcIterThread(ref(res), inicio, fin, i);
}});

Related

using std::async appear error: "No viable overloaded '='"

#include <future>
#include <thread>
#include <iostream>
#include <mutex>
void f(int n){
for(int i=0; i<n; i++){
printf("Thread[%d]: %d\n",std::this_thread::get_id(), i);
}
}
int main(int argc, const char * argv[]) {
int thCNT = 5;
std::future<int> mTH[thCNT];
for(int i=0; i<thCNT; i++){
mTH[i] = std::async(f, i+5);
}
for(int i=0; i<thCNT; i++){
mTH[i].get();
}
return 0;
}
code like above
xcode show an error like this, I dont know how to solve it.
I copy the code from an instruction, I hope to know if there is anything different between C++20 and C++11, since the instruction is made by C++11.
273K is right.
I should return int when use future like below:
int f(int n){
for(int i=0; i<n; i++){
printf("Thread[%d]: %d\n",std::this_thread::get_id(), i);
}
return 0;
}

C++ thread library exception

I have some issues with C++ thread library. I have adapted my old code for optimization of a new problem and suddenly an uncaught exception is thrown (During runtime). Some threads are joined successfully, but there's always at least one throwing an exception. Only thing which I changed in the code, was data representation. They were earlier held in 2D arrays and now I am using 1D vectors. Here is the exact runtime error I receive:
libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: Invalid argument
Below I provide the minimal reproducible example, throwing the exact same exception like in the case of the complete code.
Here is the main function:
#include <iostream>
#include <thread>
#include <vector>
void reforming(const int, const std::vector<int>&, const std::vector<double>&, const std::vector<double>&);
int main() {
int i, k;
int spec_max = 10;
int seg_max = 4;
size_t pop_size = spec_max * seg_max;
std::vector<int> seg(pop_size);
std::vector<double> por(pop_size);
std::vector<double> por_s(pop_size);
for(i = 0; i < pop_size; i++){
if(i % 2 == 0){
seg[i] = 1;
por[i] = 0.5;
por_s[i] = 0.0015;
} else {
seg[i] = 0;
por[i] = 0.7;
por_s[i] = 0.002;
}
}
std::vector<std::thread> Ref(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}
for(auto &X : Ref){
X.join();
}
return 0;
}
and the "reforming" function:
#include <iostream>
#include <vector>
void reforming(const int m, const std::vector<int>& cat_check, const std::vector<double>& por,
const std::vector<double>& por_s){
std::cout << m << " Hello from the thread\n";
}
I am using the CLion software on MacOS Catalina and currently have no other OS available to test the code.
The following code:
std::vector<std::thread> Ref(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}
creates 2 * spec_max threads, the first spec_max threads are default-initialized. Trying to join a default-initialized thread throws std::system_error.
A fix:
std::vector<std::thread> Ref;
Ref.reserve(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}

Creating a vector of threads [duplicate]

i'm new in c++ programing and need some help to use a thread library with vector library...
first I follow this tutorial
but the compiler (visual studio 2013) show me errors and I don't know how correct it:
first declaration of function
void Fractal::calcIterThread(vector<vector<iterc>> &matriz, int desdePos, int hastaPos, int idThread){
...
}
in main loop
vector<vector<iterc>> res;
res.resize(altoPantalla);
for (int i = 0; i < altoPantalla; i++){
res[i].resize(anchoPantalla);
}
int numThreads = 10;
vector<thread> workers(numThreads);
for (int i = 0; i < numThreads; i++){ //here diferent try
thread workers[i] (calcIterThread, ref(res), inicio, fin, i)); // error: expresion must have a constant value
workers[i] = thread(calcIterThread, ref(res), inicio, fin, i)); // error: no instance of constructor "std::thread::thread" matches the argument list
}
...rest of code...
thanks for any help to clarify
Try this:
#include <functional>
#include <thread>
#include <vector>
// ...
int numThreads = 10;
std::vector<std::thread> workers;
for (int i = 0; i != numThreads; ++i)
{
workers.emplace_back(calcIterThread, std::ref(res), inicia, fin, i);
}
for (auto & t : workers)
{
t.join();
}
finally I can solve the problem with this change in my code...
workers.emplace_back(thread{ [&]() {
calcIterThread(ref(res), inicio, fin, i);
}});

Emplace back thread on vector

Why this cause undefined behavior?
#include <iostream>
#include <thread>
#include <vector>
std::vector<std::thread> threads(3);
void task() { std::cout<<"Alive\n";}
void spawn() {
for(int i=0; i<threads.size(); ++i)
//threads[i] = std::thread(task);
threads.emplace_back(std::thread(task));
for(int i=0; i<threads.size(); ++i)
threads[i].join();
}
int main() {
spawn();
}
If I will create threads as in commented line thread is copied/moved assignment so its fine, but why is not working when creating thread in place?
What is happening in your code is that you construct three default threads, then add three further threads.
Change:
std::vector<std::thread> threads(3);
To:
std::vector<std::thread> threads;
const size_t number_of_threads = 3;
int main() {
threads.reserve(number_of_threads);
spawn();
}
And inside spawn:
void spawn() {
for (int i = 0; i < number_of_threads; ++i) {
threads.emplace_back(std::thread(task));
}
for (int i = 0; i < threads.size(); ++i) {
threads[i].join();
}
}
When you are using emplace_back or push_back, you must not allocate the memory before, because that will call the constructor of threads. You should just reserve it.
BTW, since you are using emplace_back not push_back you can directly write:
threads.emplace_back(task);

How to create a certain number of threads based on a value a variable contains?

I have a integer variable, that contains the number of threads to execute. Lets call it myThreadVar. I want to execute myThreadVar threads, and cannot think of any way to do it, without a ton of if statements. Is there any way I can create myThreadVar threads, no matter what myThreadVar is?
I was thinking:
for (int i = 0; i < myThreadVar; ++i) { std::thread t_i(myFunc); }, but that obviously won't work.
Thanks in advance!
Make an array or vector of threads, put the threads in, and then if you want to wait for them to finish have a second loop go over your collection and join them all:
std::vector<std::thread> myThreads;
myThreads.reserve(myThreadVar);
for (int i = 0; i < myThreadVar; ++i)
{
myThreads.push_back(std::thread(myFunc));
}
While other answers use vector::push_back(), I prefer vector::emplace_back(). Possibly more efficient. Also use vector::reserve(). See it live here.
#include <thread>
#include <vector>
void func() {}
int main() {
int num = 3;
std::vector<std::thread> vec;
vec.reserve(num);
for (auto i = 0; i < num; ++i) {
vec.emplace_back(func);
}
for (auto& t : vec) t.join();
}
So, obvious the best solution is not to wait previous thread to done. You need to run all of them in parallel.
In this case you can use vector class to store all of instances and after that make join to all of them.
Take a look at my example.
#include <thread>
#include <vector>
void myFunc() {
/* Some code */
}
int main()
{
int myThreadVar = 50;
std::vector <thread> threadsToJoin;
threadsToJoin.resize(myThreadVar);
for (int i = 0; i < myThreadVar; ++i) {
threadsToJoin[i] = std::thread(myFunc);
}
for (int i = 0; i < threadsToJoin.size(); i++) {
threadsToJoin[i].join();
}
}
#include <iostream>
#include <thread>
void myFunc(int n) {
std::cout << "myFunc " << n << std::endl;
}
int main(int argc, char *argv[]) {
int myThreadVar = 5;
for (int i = 0; i < myThreadVar; ++i) {
std::cout << "Launching " << i << std::endl;
std::thread t_i(myFunc,i);
t_i.detach();
}
}
g++ -std=c++11 -o 35106568 35106568.cpp
./35106568
Launching 0
myFunc 0
Launching 1
myFunc 1
Launching 2
myFunc 2
Launching 3
myFunc 3
Launching 4
myFunc 4
You need to store the thread so you can send it to join.
std::thread t[myThreadVar];
for (int i = 0; i < myThreadVar; ++i) { t[i] = std::thread(myFunc); }//Start all threads
for (int i = 0; i < myThreadVar; ++i) {t[i].join;}//Wait for all threads to finish
I think this is valid syntax, but I'm more used to c so I am unsure if I initialized the array correctly.