我写了这个示例程序来模仿我试图在一个更大的程序中做什么。线程与原子和互斥类的内部类
我有一些数据会来自用户,并被传递到一个线程进行一些处理。我正在使用数据周围的互斥标记来标记有数据时的信号。
使用lambda表达式,是指向*发送到线程的指针吗?我似乎正在得到我期望在cout声明中的行为。
互斥数据是否正确使用了数据?
是否将原子和互斥体作为该类的私人成员的一个好动作?
foo.h中
#pragma once
#include <atomic>
#include <thread>
#include <vector>
#include <mutex>
class Foo
{
public:
Foo();
~Foo();
void StartThread();
void StopThread();
void SendData();
private:
std::atomic<bool> dataFlag;
std::atomic<bool> runBar;
void bar();
std::thread t1;
std::vector<int> data;
std::mutex mx;
};
foo.c的
#include "FooClass.h"
#include <thread>
#include <string>
#include <iostream>
Foo::Foo()
{
dataFlag = false;
}
Foo::~Foo()
{
StopThread();
}
void Foo::StartThread()
{
runBar = true;
t1 = std::thread([=] {bar(); });
return;
}
void Foo::StopThread()
{
runBar = false;
if(t1.joinable())
t1.join();
return;
}
void Foo::SendData()
{
mx.lock();
for (int i = 0; i < 5; ++i) {
data.push_back(i);
}
mx.unlock();
dataFlag = true;
}
void Foo::bar()
{
while (runBar)
{
if(dataFlag)
{
mx.lock();
for(auto it = data.begin(); it < data.end(); ++it)
{
std::cout << *it << '\n';
}
mx.unlock();
dataFlag = false;
}
}
}
的main.cpp
#include "FooClass.h"
#include <iostream>
#include <string>
int main()
{
Foo foo1;
std::cout << "Type anything to end thread" << std::endl;
foo1.StartThread();
foo1.SendData();
// type something to end threads
char a;
std::cin >> a;
foo1.StopThread();
return 0;
}
使用std :: lock_guard,而不是手动调用mx.lock()/解锁() –
当您启动线程,你应该是'加入() 'it or'detach()' –
@DmitryKatkevich为什么?他稍后加入()'... – vu1p3n0x