C++11线程等待
C++11 thread wait
Thread.h类实现了类似Java中Thread类的run方法,因此每个继承Thread的类都实现了run。
在下面的例子中,运行两个线程:Producer和Reader,第一个(Producer)在无限循环中打印计数器,第二个线程(Reader)1)调用Produce上的wait,2)写入一些int,3)使用notify方法weakup Produce。Wait使用condition_variable变量。
问题是Reader::run方法内部的"producer->wait();"没有阻止producer,而是继续写入,怎么了?
使用编译
g++ -std=c++11 -pthread main.cpp
提前感谢
//in main.cpp
int main() {
Producer p ;
Reader r ( &p );
p.start();
r.start();
p.join();
r.join();
cout << "end" << endl << flush;
}
类:
// in main.cpp
#include <iostream>
#include <unistd.h>
#include "Thread.h"
class Producer : public Thread {
public:
Producer() {i = 0;}
virtual void run() ;
private:
int i;
};
void Producer::run() {
while ( 1 ) {
usleep ( 1000 );
cout << "Producer count: " << i++ << endl << flush;
};
};
阅读器类
// in main.cpp
class Reader : public Thread {
public:
Reader ( Producer* p ) {producer = p; i = 0;}
virtual void run() ;
private:
int i;
Producer* producer;
};
void Reader::run() {
while ( 1 ) {
usleep ( 1000 );
i++;
if ( ! ( i % 1000 ) ) {
cout << "waiting Producer" << endl << flush;
producer->wait();
cout << "write 10000 int" << endl << flush;
for ( int k = 0; k < 1000; k++ ) {
usleep ( 1000 );
cout << " Reader: count " << k << endl << flush;
}
producer->notify();
}
};
};
线程.h:
#ifndef THREAD_H_
#define THREAD_H_
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
class Runnable {
public:
virtual void run() = 0;
};
class Thread: virtual public Runnable {
private:
mutex mtx;
condition_variable cv;
thread* theThread;
Runnable * _runnable;
Runnable * execRunnable;
static void * __run ( void * cthis ) {
static_cast<Runnable*> ( cthis )->run();
return nullptr;
}
public:
Thread() :
_runnable ( nullptr ) {
theThread = nullptr;
execRunnable = this;
}
virtual ~Thread() {
if ( theThread ) {
theThread->detach();
delete theThread;
theThread = nullptr;
}
}
void wait ( ) {
unique_lock<std::mutex> lk ( mtx );
cv.wait ( lk );
}
void notify() {
cv.notify_all();
}
void start() {
if ( this->_runnable != nullptr ) {
execRunnable = this->_runnable;
}
if ( theThread ) {
delete theThread;
}
theThread = new thread ( __run, execRunnable );
}
void join() {
if ( theThread ) {
theThread->join();
delete theThread;
theThread = nullptr;
}
}
bool isJoinable() {
return theThread->joinable();
}
void stop() {
if ( theThread ) {
theThread->detach();
delete theThread;
theThread = nullptr;
}
}
};
#endif
不能像那样停止生产者线程。您需要从阅读器线程中设置一些变量,并在生产者中测试其值。然后生产者可以调用wait(),并且只有在读取器调用notify()之后才会继续。BTW.endl也会刷新,无需再次调用。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- 等待线程的最佳方式是什么
- std::thread从函数启动,无需等待线程完成
- 带有共享缓冲区的两个等待线程(生产者/消费者)
- std::condition_variable::notify_one() 不会唤醒等待线程
- 在退出进程时等待线程完成
- 如何正确等待线程中的信号
- 如何等待线程直到它开始运行
- 在纯虚拟类的析构函数中等待线程死亡会导致运行时错误
- 更改可报警/可等待线程的上下文
- C++11 std::线程并等待线程完成
- 我如何在Qt中等待线程完成而不阻塞其执行
- Notify_all不唤醒等待线程
- 如何使用boost条件变量来等待线程完成处理
- 等待线程结束(c++)
- 等待线程超时:冻结
- 等待线程
- 等待线程/s直到另一个线程/s结束
- 有效地等待线程池中的所有任务完成