Skip to content

Commit

Permalink
Use semaphores for thread synchronization
Browse files Browse the repository at this point in the history
  • Loading branch information
licy183 committed Dec 19, 2023
1 parent 51cdec5 commit 3139491
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 24 deletions.
2 changes: 1 addition & 1 deletion Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# <https://www.gnu.org/licenses/>.

SUBDIRS = tests
AM_CXXFLAGS = -std=c++11 -Wall -Wextra -pedantic -pthread
AM_CXXFLAGS = -std=c++20 -Wall -Wextra -pedantic -pthread

bin_PROGRAMS = termux-elf-cleaner

Expand Down
38 changes: 15 additions & 23 deletions elf-cleaner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ along with termux-elf-cleaner. If not, see
#include <unistd.h>

#include <algorithm>
#include <deque>
#include <mutex>
#include <future>
#include <semaphore>
#include <thread>
#include <vector>

Expand Down Expand Up @@ -64,8 +64,6 @@ int api_level = 21;
bool dry_run = false;
bool quiet = false;

std::mutex mutex;

static char const *const usage_message[] =
{ "\
\n\
Expand Down Expand Up @@ -311,16 +309,6 @@ int parse_file(const char *file_name)
return 0;
}

void parse_file_handler(std::deque<const char*>* files, unsigned int &pos) {
while (files->size() > pos) {
mutex.lock();
const char *file = files->at(pos);
pos++;
mutex.unlock();
parse_file(file);
}
}

int main(int argc, char **argv)
{
int skip_args = 0;
Expand Down Expand Up @@ -362,15 +350,19 @@ int main(int argc, char **argv)
if (argc - (skip_args + 1) <= threads_count) threads_count = files_count;
if (threads_count < 1) threads_count = 1;

std::deque<const char*> files;
std::vector<std::thread> threads(threads_count);
unsigned int pos = 0;
std::vector<std::future<void>> futures;
std::counting_semaphore sem(threads_count);

for (int i = skip_args + 1; i < argc; i++) {
sem.acquire();
const char* file = argv[i];
futures.push_back(std::async([file, &sem]() {
parse_file(file);
sem.release();
}));
}

for (auto& future : futures) future.get();

for (int i = skip_args + 1; i < argc; i++)
files.push_back(argv[i]);
for (int i = 0; i < threads_count; i++)
threads[i] = std::thread(parse_file_handler, &files, std::ref(pos));
for (std::thread& thread : threads)
if (thread.joinable()) thread.join();
return 0;
}

0 comments on commit 3139491

Please sign in to comment.