Программа зависает (оставляя все ее дочерние программы запущенными) всякий раз, когда я указываю количество потоков, равное 1, но всегда завершает работу, как ожидалось, когда количество потоков равно 1.Минимальный воспроизводимый пример проблемы приведен ниже:
Код: Выделить всё
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
atomic running(true);
mutex coutMutex;
void handle_signal(int signal) {
if (signal == SIGINT) {
running = false;
}
}
class ThreadPool {
vector threads;
queue taskQueue;
mutex queueMutex;
condition_variable cv;
atomic stop;
public:
ThreadPool(size_t threadCount) : stop(false) {
for (size_t i = 0; i < threadCount; ++i) {
threads.emplace_back([this] {
while (true) {
function task;
{
unique_lock lock(queueMutex);
cv.wait(lock, [this] { return stop || !taskQueue.empty(); });
if (stop && taskQueue.empty()) return;
task = std::move(taskQueue.front());
taskQueue.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
unique_lock lock(queueMutex);
stop = true;
}
cv.notify_all();
for (thread& t : threads) {
t.join();
}
}
void enqueueTask(function task) {
{
unique_lock lock(queueMutex);
taskQueue.push(std::move(task));
}
cv.notify_one();
}
};
void workerFunction(size_t start, size_t end, const vector& args) {
int pipefd[2];
if (pipe(pipefd) < 0) {
perror("pipe");
return;
}
// Set the write end of the pipe to non-blocking
int flags = fcntl(pipefd[1], F_GETFL, 0);
fcntl(pipefd[1], F_SETFL, flags | O_NONBLOCK);
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return;
}
if (pid == 0) {
// In the child process
close(pipefd[1]); // Close unused write end
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
execvp("cat", const_cast(args.data()));
perror("execvp");
exit(EXIT_FAILURE);
} else {
// In the parent process
close(pipefd[0]); // Close unused read end
string data = "Example data ";
for (size_t i = start; i < end && running; ++i) {
size_t written = 0;
while (written < data.size() && running) {
ssize_t bytes = write(pipefd[1], data.c_str() + written, data.size() - written);
if (bytes == -1) {
perror("write");
break; // Exit the loop on error
}
written += bytes;
}
}
{
lock_guard lock(coutMutex);
cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79187446/c-threadpool-hangs-with-multiple-threads-but-works-with-a-single-thread[/url]
Мобильная версия