Fill an array from different threads simultaneously C ++

First of all, I think it’s important to say that I am new to multithreading and know very little about it. I tried to write some C ++ programs using threads, and ran into a problem (question) that I will try to explain to you now:

I wanted to use multiple threads to populate the array, here is my code:

static const int num_threads = 5;
int A[50], n;

//------------------------------------------------------------
void ThreadFunc(int tid)
{
    for (int q = 0; q < 5; q++)
    {
        A[n] = tid;
        n++;
    }
}

//------------------------------------------------------------
int main()
{
        thread t[num_threads];
        n = 0;
        for (int i = 0; i < num_threads; i++)
        {
            t[i] = thread(ThreadFunc, i);
        }

        for (int i = 0; i < num_threads; i++)
        {
            t[i].join();
        }
        for (int i = 0; i < n; i++)
            cout << A[i] << endl;

    return 0;
}

As a result of this program, I get: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2, etc.

As I understand it, the second stream begins to write elements to the array only when the first stream finishes writing all the elements to the array. The question is why the threads do not work at the same time? I mean, why don't I get something like this:

0 1 2 0 3 1 4 and so on.

Is there any way to solve this problem?

Thanks in advance.

+4
2

n , , , , , . ( ) .

-, n . , :

std::atomic<int> n;

...

A[n++] = tid;

:

std::mutex mtx;
int next_n() {
    std::unique_lock<std::mutex> lock(mtx);
    return n++;
}

n :

A[next_n()] = tid;

, , . .

+3

, .. , , , . , , , -lpthread. , , .

, . :

int n;
// ...
A[n] = tid; n++;

std::atomic_int n;
// ...
A[n++] = tid;

. , , , , :

void ThreadFunc(int tid, int first, int last)
{
    for (int i = first; i < last; i++)
        A[i] = tid;
}

, :

for (int first = 0, i = 0; i < num_threads; i++) {
    // possible num_threads does not evenly divide ASIZE.
    int last = (i != num_threads-1) ? std::size(A)/num_threads*(i+1) : std::size(A);
    t[i] = thread(ThreadFunc, i, first, last);
    first = last;
}

, , , .

0

Source: https://habr.com/ru/post/1654910/


All Articles