- 不加锁的实现
- #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;
}
执行结果如下图所示:
理解就这么多。多线程很有意思的操作。