主线程给list 添加元素,其他七个线程打印,我每个线程给的是list的复制。
7个线程都不会退出,打印也不会送0开始,如果给list的引用会从0开始。
下面是代码
```c++
#include <iostream>
#include <windows.h>
#include <thread>
#include <mutex>
#include <atomic>
#include <list>
using namespace std;
mutex mu_all;
condition_variable cv_all;
atomic<bool> flag_all = false;
//class _Ty, class _Alloc = allocator<_Ty>
void func_1(list<int> Tem)
{
thread th_1([&Tem]() {
auto & b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b]{return b.load(); });
}
for (auto item : Tem)
{
cout << "func_1->>>" << item << endl;
}
cout << "func_1->>>" << "==============================================" << endl;
});
th_1.detach();
}
void func_2(list<int> Tem)
{
thread th_2([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b]{return b.load(); });
}
for (auto item : Tem)
{
cout<<"func_2->>>" << item << endl;
}
cout << "func_2->>>" << "==============================================" << endl;
});
th_2.detach();
}
void func_3(list<int> Tem)
{
thread th_3([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b] {return b.load(); });
}
for (auto item : Tem)
{
cout << "func_3->>>" << item << endl;
}
cout << "func_3->>>" << "==============================================" << endl;
});
th_3.detach();
}
void func_4(list<int> Tem)
{
thread th_4([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b] {return b.load(); });
}
for (auto item : Tem)
{
cout << "func_4->>>" << item << endl;
}
cout << "func_4->>>" << "==============================================" << endl;
});
th_4.detach();
}
void func_5(list<int> Tem)
{
thread th_5([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b] {return b.load(); });
}
for (auto item : Tem)
{
cout << "func_5->>>" << item << endl;
}
cout << "func_5->>>" << "==============================================" << endl;
});
th_5.detach();
}
void func_6(list<int> Tem)
{
thread th_6([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b] {return b.load(); });
}
for (auto item : Tem)
{
cout << "func_6->>>" << item << endl;
}
cout << "func_6->>>" << "==============================================" << endl;
});
th_6.detach();
}
void func_7(list<int> Tem)
{
thread th_7([&Tem]() {
auto& b = flag_all;
{
unique_lock<mutex> lock_all(mu_all);
cv_all.wait(lock_all, [&b] {return b.load(); });
}
for (auto item : Tem)
{
cout << "func_7->>>" << item << endl;
}
cout << "func_7->>>" << "==============================================" << endl;
});
th_7.detach();
}
int main()
{
list<int> i_lst;
func_1(i_lst);
func_2(i_lst);
func_3(i_lst);
func_4(i_lst);
func_5(i_lst);
func_6(i_lst);
func_7(i_lst);
for (int i = 0;;i++)
{
i_lst.emplace_back(i);
if (i == 0)
{
flag_all = true;
cv_all.notify_all();
}
}
return 0;
}
```