有了前面线程创建和循环队列的基础,我们再来看一个单度、单写利用循环队列的例子,代码如下:
#include <stdio.h>
#include <pthread.h>
#include <string>
#include "circular_queue.h"
class ThreadBase {
public:
virtual ~ThreadBase() {}
void SetMessage(const char* message) {
message_ = message;
}
void Start() {
pthread_create(&thread_id_, NULL, Hook, this);
}
void* Join() {
void* ret = NULL;
pthread_join(thread_id_, &ret);
return ret;
}
virtual void Run() {
printf("%s\n", message_.c_str());
}
private:
static void* Hook(void* object) {
ThreadBase* thread_base= static_cast<ThreadBase*>(object);
thread_base->Run();
}
pthread_t thread_id_;
std::string message_;
};
class ThreadReader : public ThreadBase {
public:
ThreadReader(CircularQueue<int>* queue) : que

本文介绍了如何利用循环队列实现单读、单写操作,并探讨了无锁数据结构的应用。通过对比《编程之美》中的双线程下载例子,阐述了本例无需使用semaphore的原因及其效率优势。
最低0.47元/天 解锁文章
10万+

被折叠的 条评论
为什么被折叠?



