关于c++:C并发与多线程-4创建多个线程数据共享问题分析

2次阅读

共计 1748 个字符,预计需要花费 5 分钟才能阅读完成。

创立和期待多个线程

应用容器类简略治理多个线程。

#include <iostream>
#include <thread>
#include <vector>

using namespace std;

void thread_func(int i)
{cout << "thread_func id :" << std::this_thread::get_id() << " " << i << endl;
}

int main()
{
    cout << "main begin" << endl;

    vector<thread> threads;

    for (int i=0; i<10; ++i)
        threads.emplace_back(thread(thread_func, i));

    for (int i=0; i<10; ++i)
        threads.at(i).join();

    cout << "main end" << endl;

    return 0;
}

输入:[输入后果每次可能是不统一的,因为子线程间竞争运行未做同步解决]

main begin
thread_func id : 2 0
thread_func id : 3 1
thread_func id : 5 3
thread_func id : 6 4
thread_func id : 4 2
thread_func id : 8 6
thread_func id : 9 7
thread_func id : 7 5
thread_func id : 10 8
thread_func id : 11 9
main end

数据共享问题剖析

只读

多线程只读同一资源是平安的。

#include <iostream>
#include <thread>
#include <vector>

using namespace std;

vector<int> g_iv{1, 2, 3};

void thread_func()
{cout << "thread_func id :" << std::this_thread::get_id() << "|"<< g_iv[0] << "" << g_iv[1] <<" " << g_iv[2] << endl;
}

int main()
{
    cout << "main begin" << endl;

    thread th1(thread_func);
    thread th2(thread_func);

    th1.join();
    th2.join();

    cout << "main end" << endl;

    return 0;
}

输入:[输入后果每次可能是不统一的,因为子线程间竞争运行未做同步解决]

main begin
thread_func id : 2 | 1 2 3
thread_func id : 3 | 1 2 3
main end

同时读写

多线程同时读、写同一资源会导致异样完结。

#include <iostream>
#include <thread>
#include <queue>

using namespace std;

class Handle {
public:
    void inMsgRevQueue()
    {for (int i=0; i<100000; ++i)
        {cout << "inMsgRevQueue() :" << i << endl;
            m_queue.push(i);
        }
    }

    void outMsgRevQueue()
    {for (int i=0; i<100000; ++i)
        {if (!m_queue.empty())
            {cout << "outMsgRevQueue() :" << m_queue.front() << endl;
                m_queue.pop();}
        }
    }

private:
    queue<int> m_queue;
};

int main()
{
    cout << "main begin" << endl;

    Handle handler;

    thread th1(&Handle::inMsgRevQueue, std::ref(handler));
    thread th2(&Handle::inMsgRevQueue, std::ref(handler));

    th1.join();
    th2.join();

    cout << "main end" << endl;

    return 0;
}

输入:

......
inMsgRevQueue() : 487
inMsgRevQueue() : 488
inMsgRevQueue() : 489
inMsgRevQueue() : 490
inMsgRevQueue() : 491
inMsgRevQueue() : 410
10:39:05: 程序异样完结。
正文完
 0