0

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.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Simas
  • 97
  • 1
  • 12
  • 1
    threads can do theirs jobs in any order, looking sequentially is just one possible outcome. Why it is in this case like this one can only speculate. Your threads have very little to do, and maybe creating the 2nd thread takes more time than the first one needs to finish. While i/o is likely to make a thread get suspended and woken up later – 463035818_is_not_an_ai Sep 12 '17 at 14:02
  • use of `atomic` here is not preventing a race condition - `n++` can happen in between two `loads` – Phydeaux Sep 12 '17 at 14:04
  • First paragraph of accepted answer in the dup I linked answers your question. – AndyG Sep 12 '17 at 14:05
  • @Phydeaux: There is also a mutex to protect (so atomic is unneeded). – Jarod42 Sep 12 '17 at 14:06
  • @Jarod42 I am blind – Phydeaux Sep 12 '17 at 14:07
  • Use std::vector! –  Sep 12 '17 at 14:30

0 Answers0