I have n threads with n arrays. For example 2 threads with 2 arrays with some data (people names).
I need to write a program that creates new result array and adds data from these 2 threads
People A[15];
atomic<int> n;
mutex n_mutex;
void threadFunc(People data[], int peopleCount, int tid) {
for (int q = 0; q < peopleCount; ++q)
{
cout << "In loop" << endl;
lock_guard<mutex> lock(n_mutex);
A[n.load()].setName(data[q].getName());
A[n.load()].setArrayId(q);
A[n.load()].setThreadId(tid);
n++;
}
}
int main() {
threads[0] = thread(threadFunc, people1, allPeopleCount[0], 1);
threads[1] = thread(threadFunc, people2, allPeopleCount[1], 2);
for (auto& th : threads) {
th.join();
}
for (int i = 0; i < 6; i++)
{
cout << "Thread_" << A[i].getThreadId() << " " << A[i].getArrayId() << " name: " << A[i].getName() << endl;
}
}
And it prints in random order which is fine
Thread_1 0 name: Adam
Thread_2 0 name: John
Thread_1 1 name: Robert
Thread_1 2 name: Greg
Thread_2 1 name: David
Thread_2 2 name: Michael
However if I delete this line
cout << "In loop" << endl;
from threadFunc it prints following:
Thread_1 0 name: John
Thread_1 1 name: Adam
Thread_1 2 name: Robert
Thread_2 0 name: David
Thread_2 1 name: Greg
Thread_2 2 name: Michael
And it looks like it works sequentially. So why does it change to that when i use dont use cout to print data in console? Data is always in order without using it.