C ++线程将两个数组添加到一个结果数组

时间:2017-09-12 14:00:08

标签: c++ arrays multithreading

我有n个数组的n个线程。例如2个线程,其中2个数组包含一些数据(人名)。

我需要编写一个程序来创建新的结果数组并添加来自这两个线程的数据

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;
    }
}

它以随机顺序打印,很好

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

但是如果我删除这一行

cout << "In loop" << endl;
从threadFunc

打印以下内容:

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

看起来它按顺序工作。那么为什么当我使用不使用cout在控制台中打印数据时它会改变呢?数据始终按顺序使用而不使用它。

0 个答案:

没有答案