0

I am trying to identify the difference between std::::thread and std:async through a simple experiment.(check std::async Thread Pool functionality)

However, an error occurs during execution.

enter image description here

What's the problem and how can I fix it?

thread test.

void for_print(int num) {
    for (int i = 0; i < 1000; i++)
        printf("%d Thread : %d\n", num, i);
}


int main(){
    std::vector<std::thread> v_thread(2000);

    for (size_t i = 0; i < 2000; i++)
        v_thread.emplace_back(std::thread(for_print, i));

    //join()
    for (size_t i = 0; i < 2000; i++)
        v_thread[i].join();

    std::vector<std::thread>().swap(v_thread);
    return 0;
}

async test

void for_print(int num) {
    for (int i = 0; i < 1000; i++)
        printf("%d async : %d\n", num, i);
}

int main() {
    std::vector<std::future<void>> v_async(2000);

    for (size_t i = 0; i < 2000; i++)
        v_async.emplace_back(std::async(std::launch::async, for_print, i));

    for (size_t i = 0; i < 2000; i++)
        v_async[i].wait();

    std::vector<std::future<void>>().swap(v_async);
    return 0;
}
Hwan E
  • 566
  • 2
  • 13

1 Answers1

2
std::vector<std::thread> v_thread(2000);

for (size_t i = 0; i < 2000; i++)
   v_thread.emplace_back(std::thread(for_print, i));

for (size_t i = 0; i < 2000; i++)
   v_thread[i].join();

This is wrong. You first create a vector of 2000 "empty" thread objects, then add additional 2000 "living" threads, and finally join those first 2000 thread, which are not joinable.

The same holds in the case of std::async.

Just change

std::vector<std::thread> v_thread(2000);

to

std::vector<std::thread> v_thread;

and

std::vector<std::future<void>> v_async(2000);

to

std::vector<std::future<void>> v_async;

OT: These lines:

std::vector<std::thread>().swap(v_thread);
return 0;

at the end of main are completely superfluous.


EDIT

Also note that systems typically have some limit for the number of running threads. Creating 2000 threads might therefore be a problem also in this context.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93