并发编程队列怎么写程序

时间:2025-01-23 14:23:48 游戏攻略

并发编程队列的实现方式有多种,以下是一些常见的方法和代码示例:

1. 使用互斥锁(Mutex)实现队列

```cpp

include

include

template

class Queue {

private:

std::list _list;

pthread_mutex_t _lock;

public:

Queue() {

pthread_mutex_init(&_lock, NULL);

}

~Queue() {

pthread_mutex_destroy(&_lock);

}

void enqueue(const T& item) {

pthread_mutex_lock(&_lock);

_list.push_back(item);

pthread_mutex_unlock(&_lock);

}

T dequeue() {

pthread_mutex_lock(&_lock);

if (_list.empty()) {

pthread_mutex_unlock(&_lock);

throw std::runtime_error("Queue is empty");

}

T _temp = _list.front();

_list.pop_front();

pthread_mutex_unlock(&_lock);

return _temp;

}

bool empty() const {

pthread_mutex_lock(&_lock);

bool result = _list.empty();

pthread_mutex_unlock(&_lock);

return result;

}

};

```

2. 使用条件变量(Condition)实现队列

```cpp

include

include

template

class BlockingQueue {

private:

std::queue _queue;

pthread_mutex_t _lock;

pthread_cond_t _notEmpty;

pthread_cond_t _notFull;

public:

BlockingQueue(size_t maxSize) : _notEmpty(_lock), _notFull(_lock) {

pthread_mutex_init(&_lock, NULL);

}

~BlockingQueue() {

pthread_mutex_destroy(&_lock);

pthread_cond_destroy(&_notEmpty);

pthread_cond_destroy(&_notFull);

}

void enqueue(const T& item) {

pthread_mutex_lock(&_lock);

while (_queue.size() == _queue.capacity()) {

pthread_cond_wait(&_notFull, &_lock);

}

_queue.push(item);

pthread_cond_signal(&_notEmpty);

pthread_mutex_unlock(&_lock);

}

T dequeue() {

pthread_mutex_lock(&_lock);

while (_queue.empty()) {

pthread_cond_wait(&_notEmpty, &_lock);

}

T item = _queue.front();

_queue.pop();

pthread_cond_signal(&_notFull);

pthread_mutex_unlock(&_lock);

return item;

}

bool empty() const {

pthread_mutex_lock(&_lock);

bool result = _queue.empty();

pthread_mutex_unlock(&_lock);

return result;

}

size_t size() const {

pthread_mutex_lock(&_lock);

size_t result = _queue.size();

pthread_mutex_unlock(&_lock);

return result;

}

};

```

3. 使用原子操作和CAS实现非阻塞队列