问题重述:
这里考虑原子整型,但是牛客网中原子整型出错,因此改为互斥锁,还是出错,说什么没有链接相应的文件。因此将此问题在此记录。
思路解析:
完全可以用两个变量去控制,这里考虑原子整型,但是牛客网中原子整型出错,因此改为互斥锁,还是出错,说什么没有链接相应的文件。因此将此问题在此记录。思路详见代码:
代码实现:
# include<thread>
# include<iostream>
#include<atomic>
#include<vector>
#include<mutex>
using namespace std;
//线程
vector<thread> threadPoll;
//CAS原子控制变量
//atomic_int N = 0;
//atomic_int flag = 0;
int N = 0;
int flag = 0;
string str;
mutex m;
//三个线程函数
void threadFun1()
{
while (N)
{
lock_guard<mutex> lock(m);
if (flag == 1)
{
str.push_back('B');
++flag;
}
}
}
void threadFun2()
{
while (N)
{
lock_guard<mutex> lock(m);
if (flag == 2)
{
str.push_back('C');
++flag;
}
}
}
void threadFun3()
{
while (N)
{
lock_guard<mutex> lock(m);
if (flag == 3)
{
str.push_back('D');
--N;
//防止最后依次主线程会因为N没有即时更新但是flag = 0而进行一次打印,
if (N == 0)
flag = 5;
else
flag = 0;
}
}
}
void init()
{
threadPoll.push_back(thread(threadFun1));
threadPoll.push_back(thread(threadFun2));
threadPoll.push_back(thread(threadFun3));
}
void Release()
{
for (thread &e : threadPoll)
e.join();
}
int main()
{
int n = 0;
cin >> N;
init();
while (N)
{
if (flag == 0)
{
lock_guard<mutex> lock(m);
str.push_back('A');
++flag;
}
}
Release();
cout << str << endl;
return 0;
}