c语言多线程怎么共享数据,【C++并发与多线程】 4_创建多个线程、数据共享问题分析...

创建和等待多个线程

使用容器类简单管理多个线程。#include

#include

#include

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

#include

#include

using namespace std;

vector 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

#include

#include

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

};

int main()

{

cout << "main begin" << endl;

Handle handler;

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

thread th2(&Handle::outMsgRevQueue, 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值