【发布时间】:2016-12-05 05:19:05
【问题描述】:
我编写了这个示例程序来模仿我在一个更大的程序中尝试做的事情。
我有一些数据将来自用户并被传递到线程中进行一些处理。我在数据周围使用互斥锁,当有数据时,标志会发出信号。
使用 lambda 表达式,是否将指向 *this 的指针发送到线程?我似乎在 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()/unlock() -
当你启动线程时,你应该
join()它或者detach() -
@DmitryKatkevich 为什么?他稍后会
join()ing... -
我更喜欢保存
detach以备不时之需 -
我会将您的作业转移到
dataFlag到锁内。现在我可以看到它在外面的潜在问题。
标签: c++ multithreading class mutex atomic