简体   繁体   中英

How to join an array of threads in C++?

I am learning how to use threads in C++. I need to create an array of threats, start executing all of the threats and subsequently join them. I am getting an error however, can someone help me please?

The skeleton of my code is:

#include <iostream>
#include <thread>
using namespace std;

int Numbers[100000][1000];
thread Threads[10000][1000];

// Function to be passed to thread
void Simulate(int i, int j) {
    Numbers[i][j] = i + j;
}

int main()
{
    // Start executing threads
    for (int i = 0; i < 10000; i++) {
        for (int j = 0; j < 1000; j++) {
            Threads[i][j] = thread(Simulate, i, j);
        }
    }
    // Wait till all of them finish
    for (int i = 0; i < 10000; i++) {
        for (int j = 0; j < 1000; j++) {
            if (Threads[i][j].joinable()) {
                Threads[i][j].join();
            }
        }
    }
}

I get the exception:

Unhandled exception at 0x76BF40B2 in Learn.exe: Microsoft C++ exception: std::system_error at memory location 0x1DF3F4E0.

I am aware of this question but the addition of if (Threads[i][j].joinable()) did not help. Thank you very much for any help!

Unhandled exception at 0x76BF40B2 in Learn.exe: Microsoft C++ exception: std::system_error at memory location 0x1DF3F4E0.

That mostly because you created an insane number of threads

thread Threads[10000][1000];

Most systems cannot support that number of threads. This is a typical max number of threads that a Linux system support:

~$ cat /proc/sys/kernel/threads-max
124898

Windows can be different, but most likely not in the range of millions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM