C++11新特性之多线程

多线程与互斥锁
  1. 不加锁的实现
  2. #include
    #include
    #include
    #include<condition_variable>
    using namespace std;
    int intarrEven[5] = { 0,2,4,6,8 };
    int intarrOdd[5] = { 1,3,5,7,9 };
    std::mutex mtx;
    std::condition_variable cv;
    bool ready = false;
    void display(int id)
    {
    //std::unique_lockstd::mutex lck(mtx);当前线程在执行的时候,不允许其他线程调用该函数。
    cout << "thread " << id << endl;
    }

int main()
{
std::thread threads[10];//定义多线程数组。
for (int i = 0; i < 10; i++)
{
threads[i] = std::thread(display, i*i);//为每个多线程数组赋予执行的函数和变量。
}
for (auto &x : threads)
{
x.join();//加入主线程,如果x函数需要等待,那么会阻塞主线程,直到X函数执行完毕。
}
system(“pause”);
return 0;
}
执行结果:多线程的每个线程相对独立。所以导致打印的很难看。
在这里插入图片描述
总之你执行一百次有一百中执行的结果。
我们加锁之后:就是那段mutex放开之后:
在这里插入图片描述
很整齐的打印结果
我们写一段代码实现打印两个数组交叉打印:
#include
#include
#include
#include<condition_variable>
using namespace std;
int intarrEven[5] = { 0,2,4,6,8 };
int intarrOdd[5] = { 1,3,5,7,9 };
std::mutex mtx;
std::condition_variable cvodd;//c++11新特性条件变量。可以等待某个线程唤醒。
std::condition_variable cveven;
bool ready = false;
int i = 0;
int j = 0;
bool OddEven = true;//为true的时候打印偶数,为false的打印奇数
void displayOdd()
{
std::unique_lockstd::mutex lck(mtx);
while (OddEven)
cvodd.wait(lck);//lck为条件变量,它的条件必须满足已被当前线程锁定的前提
cout << intarrOdd[i] << " ";
OddEven = true;
i++;
cveven.notify_all();
}
void displayEven()
{
std::unique_lockstd::mutex lck(mtx);
while (!OddEven)
cveven.wait(lck);
cout << intarrEven[j] << " ";
OddEven = false;
j++;
cvodd.notify_all();通知等待cvodd,可以开始干活了。
}
int main()
{
std::thread threads[10];
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
threads[i] = thread(displayEven);
}
else
{
threads[i] = thread(displayOdd);
}
}
for (auto &x : threads)
{
x.join();
}
system(“pause”);
return 0;
}

执行结果如下图所示:
在这里插入图片描述
理解就这么多。多线程很有意思的操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值