sigillum_conf
sigillum_conf

Reputation: 433

C++ multiple threads and processes in vector

While going through a c++ tutorial book(it's in Spanish so I apologize if my translation to English is not as proper as it should be) I have come across a particular code snippet that I do not fully understand in terms of the different processes that are happening in the background. For example, in terms of multiple address spaces, how would I determine if these are all withing the context of a single process(being that multiple threads are being added over each push to the vector)? How would I determine if each thread is different from the other if they have the exact same computation being made?)

#include <iostream>
#include <vector>
#include <thread>

using namespace std;

int addthreads = 0;

void squarenum(int x) {

   addthreads += x * x * x;

}

int main() {

        vector<thread> septhread;

        for (int i = 1; i <= 9; i++){

          septhread.push_back(thread(&squarenum, i));

        }

        for (auto& th : septhread){

          th.join();

        }

        cout << "Your answer = " << addthreads << endl;

        system("pause");

        return 0;

}

Every answer defaults to 2025, that much I understand. My basic issue is understanding the first part of my question.

By the way, the compiler required(if you are on Linux):

g++ -std=gnu++ -pthread threadExample.cpp -o threadExample

Upvotes: 1

Views: 1285

Answers (1)

kfsone
kfsone

Reputation: 24269

A thread is a "thread of execution" within a process, sharing the same address space, resources, etc. Depending on the operating system, hardware, etc, they may or may not run on the same CPU or CPU Thread.

A major issue with thread programming, as a result, is managing access to resources. If two threads access the same resource at the same time, Undefined Behavior can occur. If they are both reading, it may be fine, but if one is writing at the same moment the other is reading, numerous outcomes ensue. The simplest is that both threads are running on separate CPUs or cores and so the reader does not see the change made by the writer due to cache. Another is that the reader sees only a portion of the write (if it's a 64-bit value they might only see 32-bits changed).

Your code performs a read-modify-store operation, so the first thread to come along sees the value '0', calculates the result of x*x*x, adds it to 0 and stores the result.

Meanwhile the next thread comes along and does the same thing, it also sees 0 before performing its calculation, so it writes 0 + x*x*x to the value, overwriting the first thread.

These threads might not be in the order that you launched them; it's possible for thread #30 to get the first execution cycle rather than thread #1.

You may need to consider looking at std::atomic or std::mutex.

Upvotes: 2

Related Questions