我在c ++ 11中编写了一个用于测试Thread的简单程序,但是std::cout没有按照我的预期工作.
class Printer
{
public:
void exec()
{
mutex m;
m.lock();
cout<<"Hello "<<this_thread::get_id()<<endl;
chrono::milliseconds duration( 100 );
this_thread::sleep_for( duration );
m.unlock();
}
};
int main()
{
Printer printer;
thread firstThread([&printer](){
while(1)
printer.exec();
});
thread secondThread([&printer](){
while(1)
printer.exec();
});
firstThread.join();
secondThread.join();
}
Run Code Online (Sandbox Code Playgroud)
一些结果:
Hello 11376
Hello 16076
Hello 16076
Hello Hello 11376
16076
Hello 11376
,....
Run Code Online (Sandbox Code Playgroud)
我使用互斥锁来锁定线程,所以我无法理解为什么两个线程同时执行std::cout.它接缝非常适合我.任何人都可以解释发生了什么!?!
C++ 11
我试图做出vector的std::thread秒.以下三点的组合说我可以.
1.)根据http://en.cppreference.com/w/cpp/thread/thread/thread,
thread默认构造函数创建一个
不代表线程的线程对象.
2.)根据http://en.cppreference.com/w/cpp/thread/thread/operator%3D,thread的operator=
使用移动语义将[参数,即线程右值引用]的状态分配给[调用线程].
3.)根据 http://en.cppreference.com/w/cpp/container/vector/vector,仅将大小类型变量传递给向量构造函数
具有[指定数量]的值初始化(对于类的默认构造)T实例的容器.没有复制.
所以,我这样做了:
#include <iostream>
#include <thread>
#include <vector>
void foo()
{
std::cout << "Hello\n";
return;
}
int main()
{
std::vector<std::thread> vecThread(1);
vecThread.at(0) = std::thread(foo);
vecThread.at(0).join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这在VC11和g ++ 4.8.0(在线编译器)中按预期运行,如下所示:
控制台输出:
Hello
Run Code Online (Sandbox Code Playgroud)
然后我在clang 3.2中尝试了它,通过在同一个网页上切换编译器菜单,这给出了:
stderr:
pure virtual method called
terminate called without an active exception
Run Code Online (Sandbox Code Playgroud)
当一个代表线程的线程对象在join()编辑或detach()编辑之前超出范围时,程序将被强制终止.我有join()ed vecThread.at(0),所以剩下的唯一问题是临时线程 …
我正在使用C++ 11,我有一个std::thread类成员,它每2分钟向听众发送一次信息.其他它只是睡觉.所以,我让它睡了2分钟,然后发送所需的信息,然后再睡2分钟.
// MyClass.hpp
class MyClass {
~MyClass();
RunMyThread();
private:
std::thread my_thread;
std::atomic<bool> m_running;
}
MyClass::RunMyThread() {
my_thread = std::thread { [this, m_running] {
m_running = true;
while(m_running) {
std::this_thread::sleep_for(std::chrono::minutes(2));
SendStatusInfo(some_info);
}
}};
}
// Destructor
~MyClass::MyClass() {
m_running = false; // this wont work as the thread is sleeping. How to exit thread here?
}
Run Code Online (Sandbox Code Playgroud)
问题:
这种方法的问题是我无法在线程休眠时退出线程.我从阅读中理解,我可以使用a唤醒它std::condition_variable并优雅地退出?但我正在努力寻找一个简单的例子,它可以满足上述场景中的要求.condition_variable我发现的所有例子看起来都太复杂了,我想在这里做些什么.
问题:
如何std::condition_variable在睡眠时使用a 唤醒线程并正常退出?或者,没有这种condition_variable技术,还有其他方法可以实现相同的目标吗?
另外,我看到我需要std::mutex结合使用std::condition_variable?这真的有必要吗?通过将std::condition_variable逻辑仅添加到代码中的所需位置,是否无法实现目标? …
我想从Qt中的C++线程(std :: thread)发出信号.
我该怎么做?
我正在尝试学习c ++ 11线程并拥有以下代码:
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
void add(int& i){
std::mutex some_mutex;
// std::cout << " I am " << std::endl;
std::lock_guard<std::mutex> guard(some_mutex);
i++;
}
int main(){
int i = 0;
std::vector<std::thread> vec_threads;
for(int i = 0; i < 10; i++){
vec_threads.push_back(std::thread(add,std::ref(i)));
}
std::for_each(vec_threads.begin(),vec_threads.end(),
std::mem_fn(&std::thread::join));
std::cout<< " i = " << i << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个vectorhold std::thread,我从每个线程调用add函数并通过ref传递i.在我假设线程会做(添加i = i+1)之后,最终结果并不反映我想要的.
输出:i = 0
预期产出:i = 10
对于需要使用线程跨越的函数,是否可能存在重载?
我有一个名为Complex的简单类.
class Complex
{
public:
Complex():realPart_(0), imagPart_(0){}
Complex(double rp, double ip) : realPart_(rp), imagPart_(ip) {}
double & real() { return realPart_;}
double & imag() { return imagPart_;}
const double & real() const { return realPart_;}
const double & imag() const { return imagPart_;}
double square() const {return realPart_*realPart_ - imagPart_*imagPart_;}
void display() const
{
std::cout << "Square of the Complex number (" << realPart_ << ") + i (" << imagPart_ << " ) is " << square() << …Run Code Online (Sandbox Code Playgroud) 在以下代码段中,
void foo() {
std::this_thread::native_handle().... //error here
}
int main() {
std::thread t1(foo);
t1.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你如何获得的native_handle从std::this_thread从函数内foo?
如何std::thread::id在C++中对字符串进行类型转换?我试图将生成的输出强制转换 std::this_thread::get_id()为字符串或char数组.
我目前在我的线程池中有一个带有x worker 的程序.在主循环Ÿ任务分配给工人来完成,但之后的任务被发送出去,我必须与节目之前之前等待所有任务完成.我相信我目前的解决方案效率低下,必须有更好的方法等待所有任务完成,但我不知道如何去解决这个问题
// called in main after all tasks are enqueued to
// std::deque<std::function<void()>> tasks
void ThreadPool::waitFinished()
{
while(!tasks.empty()) //check if there are any tasks in queue waiting to be picked up
{
//do literally nothing
}
}
Run Code Online (Sandbox Code Playgroud)
更多信息:
线程池结构
//worker thread objects
class Worker {
public:
Worker(ThreadPool& s): pool(s) {}
void operator()();
private:
ThreadPool &pool;
};
//thread pool
class ThreadPool {
public:
ThreadPool(size_t);
template<class F>
void enqueue(F f);
void waitFinished();
~ThreadPool();
private:
friend class Worker; …Run Code Online (Sandbox Code Playgroud) 我有一些代码std::thread从C++ 11 <thread>标头动态分配一个新的代码,如下所示:
std::thread *th = new thread( /* my args */);
Run Code Online (Sandbox Code Playgroud)
一段时间后,我打电话给加入:
th->join();
Run Code Online (Sandbox Code Playgroud)
由于我动态分配了线程,我是否还需要调用delete th;以释放内存?如果我这样做,我还需要先打个电话join()吗?