Suppose I have a queue of pointers to std::string
and producer and consumer threads working on the queue. Let's say a producer appends to a string and puts the pointer in the queue. A consumer thread gets the pointer, appends another data to the string and puts the pointer to another queue.
- Will the consumer thread read an updated data from the producer thread?
- After the consumer updates the data and puts it in another queue, will consumers to that queue see the updates of the producer and the consumer thread from (1)?
EDIT: sample code EDIT: Added complete example
#include <deque>
#include <thread>
#include <string>
#include <iostream>
#include <mutex>
#include <atomic>
class StringQueue {
public:
std::string* pop() {
std::unique_lock<std::mutex> lock(_mutex);
if (_queue.empty())
return NULL;
std::string* s = _queue.front();
_queue.pop_front();
return s;
}
void push(std::string* s) {
std::unique_lock<std::mutex> lock(_mutex);
_queue.push_back(s);
}
private:
std::deque<std::string*> _queue;
std::mutex _mutex;
};
int main(int argc, char** argv)
{
StringQueue job_queue;
StringQueue result_queue;
std::atomic<bool> run(true);
std::thread consumer([&job_queue, &result_queue, &run]{
while (run.load()) {
std::string* s = job_queue.pop();
if (s != nullptr)
s->append("BAR");
result_queue.push(s);
}
});
std::thread result_thread([&result_queue, &run]{
while (run.load()) {
std::string* s = result_queue.pop();
if (s != nullptr) {
std::cout << "Result: " << *s << std::endl;
delete s;
}
}
});
std::string input;
while (true)
{
std::cin >> input;
if (input == "STOP")
break;
std::string* s = new std::string(input);
job_queue.push(s);
}
run.store(false);
result_thread.join();
consumer.join();
}