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.