#c #multithreading #thread-safety
Вопрос:
У меня возникли проблемы с вызовом putSome(TSQueue*)
, я нашел этот код из учебника и переключал «Потоки» на обычный поток.
Главные виновники, похоже, находятся где-то поблизости. emplace_back()
Как я могу использовать emplace_back
, чтобы принять TSQueue в качестве входных данных?
// Start worker threads to insert.
for (i = 0; i < 3; i ) {
queues[i] = new TSQueue();
workers[i].emplace_back(putSome, amp;workers);
}
#include <mutex>
#include <thread>
#include <vector>
using namespace std;
// Prototypes
void testRemoval(TSQueue *queue);
void *putSome(void *p);
// Thread-safe queue interface
const int MAX = 10;
class TSQueue {
// Synchronization variables
// Lock lock;
std::mutex mtx;
// State variables
int items[MAX];
int front;
int nextEmpty;
public:
TSQueue();
~TSQueue(){};
bool tryInsert(int item);
bool tryRemove(int *item);
};
// Initialize the queue to empty
// and the lock to free.
TSQueue::TSQueue() {
front = nextEmpty = 0;
}
// Try to insert an item. If the queue is
// full, return false; otherwise return true.
bool
TSQueue::tryInsert(int item) {
bool success = false;
//lock.acquire();
mtx.lock();
if ((nextEmpty - front) < MAX) {
items[nextEmpty % MAX] = item;
nextEmpty ;
success = true;
}
// lock.release();
mtx.unlock();
return success;
}
// Try to remove an item. If the queue is
// empty, return false; otherwise return true.
bool
TSQueue::tryRemove(int *item) {
bool success = false;
// lock.acquire();
mtx.lock();
if (front < nextEmpty) {
*item = items[front % MAX];
front ;
success = true;
}
// lock.release();
mtx.unlock();
return success;
}
// TSQueueMain.cc
// Test code for TSQueue.
int main(int argc, char **argv) {
TSQueue *queues[3];
// std::thread workers[3];
vector<thread> workers;
int i, j;
// Start worker threads to insert.
for (i = 0; i < 3; i ) {
queues[i] = new TSQueue();
workers[i].emplace_back(putSome, amp;workers);
}
// Wait for some items to be put.
workers[0].join();
// Remove 20 items from each queue.
for (i = 0; i < 3; i ) {
printf("Queue %d:n", i);
testRemoval(queues[i]);
}
}
// Insert 50 items into a queue.
void *putSome(void *p) {
TSQueue *queue = (TSQueue *)p;
int i;
for (i = 0; i < 50; i ) {
queue->tryInsert(i);
}
return NULL;
}
// Remove 20 items from a queue.
void testRemoval(TSQueue *queue) {
int i, item;
for (i = 0; i < 20; i ) {
if (queue->tryRemove(amp;item))
printf("Removed %dn", item);
else
printf("Nothing there.n");
}
}
Комментарии:
1. emplace_back попытается вызвать конструктор для std::thread с аргументами putSome и указателем на вектор потоков. И в std::потоке нет такого конструктора