dimanche 23 juillet 2017

C++ error: 'operator=' is a private member of 'std::__1::thread'

I'm using Eclipse Neon and trying to create a basic example of concurrent counters that increment and decrement by 20, but the build won't compile. Two lines of my code are being highlighted and both are showing the following error:

'operator=' is a private member of 'std::__1::thread'

The lines in question are:

upThreads[i] = std::thread(increment20);
downThreads[i] = std::thread(decrement20);

The full code:

#include <thread>
#include <iostream>
#include <mutex>

using namespace std;

std::mutex mymutex;
int counter;

void increment20() {
    std::lock_guard<std::mutex> guard(mymutex);
    for (int i = 0; i < 20; i++) {
        ++counter;
    }
}

void decrement20() {
    std::lock_guard<std::mutex> guard(mymutex);
    for (int i = 0; i < 20; i++) {
        --counter;
    }
}

int main() {

    std::thread upThreads[10];
    std::thread downThreads[10];

    for (int i = 0; i < 10; ++i) {
        upThreads[i] = std::thread(increment20);
        downThreads[i] = std::thread(decrement20);
    }

    for (int i = 0; i < 10; ++i) {
        upThreads[i].join();
        downThreads[i].join();
    }

    std::cout << "final value: " << counter << std::endl;

    return 0;
}

Any help would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire