From e4dc56989495710b4a338d5161ee35520c49eb47 Mon Sep 17 00:00:00 2001 From: Annie_wang Date: Wed, 10 May 2023 16:37:19 +0800 Subject: [PATCH] update docs Signed-off-by: Annie_wang --- base/include/directory_ex.h | 87 +++++++------- base/include/file_ex.h | 100 +++++++++------- base/include/mapped_file.h | 2 +- base/include/safe_block_queue.h | 117 +++++++++--------- base/include/safe_map.h | 72 +++++------ base/include/safe_queue.h | 32 ++--- base/include/semaphore_ex.h | 206 ++++---------------------------- base/include/thread_ex.h | 70 ++++++----- base/include/thread_pool.h | 54 +++++---- 9 files changed, 304 insertions(+), 436 deletions(-) diff --git a/base/include/directory_ex.h b/base/include/directory_ex.h index 9312c56..acada4c 100644 --- a/base/include/directory_ex.h +++ b/base/include/directory_ex.h @@ -23,129 +23,136 @@ namespace OHOS { /** - * @brief Get the full absolute path to the current program. + * @brief Obtains the full absolute path of this program. * - * /proc/self/exe represents the current program, and its source path can be - * read with the readlink function to get the absolute path of the current - * program. + * /proc/self/exe indicates the program, and you can obtain its absolute + * path by using readlink(). */ std::string GetCurrentProcFullFileName(); std::string GetCurrentProcFullFileName(); /** - * @brief Get the absolute path of the current program. + * @brief Obtains the absolute path of this program. */ std::string GetCurrentProcPath(); /** - * @brief Obtain the path to the corresponding file by the full path. + * @brief Obtains the path of a file based on the full path. */ std::string ExtractFilePath(const std::string& fileFullName); /** - * @brief Obtain the name to the corresponding file by the full path. + * @brief Obtains the name of a file based on the full path. */ std::string ExtractFileName(const std::string& fileFullName); /** - * @brief Obtain the filename extension to the corresponding file by the full - * path. + * @brief Obtains the filename extension based on the full path. + * */ std::string ExtractFileExt(const std::string& fileName); /** - * @brief Exclude the end '/' from the strPath. + * @brief Excludes the trailing path delimiter '/' from the strPath. * - * Determine whether the path has ended with '/', and returns the path after - * removing '/', otherwise returns the path directly. + * If the path ends with '/', returns the path after removing '/'. + * Otherwise, returns the path directly. */ std::string ExcludeTrailingPathDelimiter(const std::string& path); /** - * @brief Include the end '/' from the strPath. + * @brief Includes the trailing path delimiter '/' in the strPath. * - * Determine whether the path has ended with "/", and returns the path after - * adding '/', otherwise returns the path directly. + * If the path ends with "/", returns the path. + * Otherwise, returns the path with an appended delimiter. */ std::string IncludeTrailingPathDelimiter(const std::string& path); /** - * @brief Get names of all files under `path` recursively. + * @brief Obtains the names of all files in the specified directory recursively. * - * @param path Input path. - * @param files Target `std::vector` to store the file names. + * @param path Indicates the target directory. + * @param files Indicates the std::vector to store the file names. */ void GetDirFiles(const std::string& path, std::vector& files); /** - * @brief Judge if the path is empty. + * @brief Checks whether a folder is empty. * - * @return Return true if is empty, else false. + * @return Returns true if the folder is empty; + * returns false otherwise. */ bool IsEmptyFolder(const std::string& path); /** - * @brief Create the dir recursively. + * @brief Creates a directory recursively. * - * Parent directory can be created at the same time when it does not exist. + * The parent directory can be created at the same time when it does not exist. * - * @note If there are problems such as 'Permission Denied', the creation may + * @note If there are errors such as 'Permission Denied', the creation may * also fail. - * @return Return true if create success, else false. + * @return Returns true if the directory is created; + * returns false otherwise. */ bool ForceCreateDirectory(const std::string& path); /** - * @brief Delete the specified dir. + * @brief Deletes a directory. * - * All subdirs and files will also be deleted. + * All subdirectories and files in the specified directory will also be deleted. * * @note It is not necessarily successful to delete. - * @note If there are problems such as 'Permission Denied', the deletion may + * @note If there are errors such as 'Permission Denied', the deletion may * also fail. - * @return Return true if delete success, else false. + * @return Returns true if the directory is deleted; + * returns false otherwise. */ bool ForceRemoveDirectory(const std::string& path); /** - * @brief Remove the file specified by fileName. + * @brief Removes the file specified by fileName. * - * @return Return true if remove success, else false. + * @return Returns true if the file is removed; + * returns false otherwise. */ bool RemoveFile(const std::string& fileName); /** - * @brief Get the folder size(bytes). + * @brief Obtains the folder size, in bytes. */ uint64_t GetFolderSize(const std::string& path); /** - * @brief Change the file authority. + * @brief Changes the access permissions on a file. * - * @param mode Specify the changed permissions, see chmod(). - * @return Return true if change success, else false. + * @param mode Indicates the permissions on the file. + * For details, see chmod(). + * @return Returns true if the permissions are changed; + * returns false otherwise. */ bool ChangeModeFile(const std::string& fileName, const mode_t& mode); /** - * @brief Change authority of the directory specified by path and all of its + * @brief Changes the access permissions on a directory and all its * subdirectories. * - * @param mode Specify the changed permissions, see chmod(). - * @return Return true if change success, else false. + * @param mode Indicates the permissions. For details, see chmod(). + * @return Returns true if the permissions are changed; + * returns false otherwise. */ bool ChangeModeDirectory(const std::string& path, const mode_t& mode); /** - * @brief Get real path from relative path. + * @brief Obtains the real path from a relative path. * - * @return Return true if get success, else false. + * @return Returns true if the real path is obtained; + * returns false otherwise. */ bool PathToRealPath(const std::string& path, std::string& realPath); #if defined(IOS_PLATFORM) || defined(_WIN32) /** - * @brief The TransformFileName function transform the input file name for windows or mac. + * @brief Transforms a file name to that for Windows or macOS. */ std::string TransformFileName(const std::string& fileName); #endif diff --git a/base/include/file_ex.h b/base/include/file_ex.h index e1d1f3d..17a0663 100644 --- a/base/include/file_ex.h +++ b/base/include/file_ex.h @@ -15,15 +15,16 @@ /** @file file_ex.h * -* @brief Provide global file operation functions implemented in c_utils. +* @brief Provides global file operation functions implemented in c_utils. */ /** * @defgroup FileReadWrite * @{ -* @brief To read from and write to files. +* @brief Provides interfaces for reading data from and writing data to files. * -* Include reading from or writting to files and searching for specified strings. +* You can use the interfaces to read data from a file, write data to a file, +* and search for the specified string. */ #ifndef UTILS_BASE_FILE_EX_H @@ -35,96 +36,107 @@ namespace OHOS { /** * @ingroup FileReadWrite - * @brief Read contents as a string from the specified file. + * @brief Reads a string from a file. * - * @param filePath Path of the specified file. - * @param content Target `std::string` object to store the result. - * @return Return true on success, false if any error occurs. - * @note Maximum size of the file is 32MB. + * @param filePath Indicates the path of the target file. + * @param content Indicates the std::string object used to hold + * the data read. + * @return Returns true if the string is read successfully; + * returns false otherwise. + * @note The maximum file size is 32 MB. */ bool LoadStringFromFile(const std::string& filePath, std::string& content); /** * @ingroup FileReadWrite - * @brief Write contents of a string to the specified file. + * @brief Writes a string to a file. * - * @param filePath Path of the specified file. - * @param content Target `std::string` object to be written to the file. - * @param truncated Specify if truncated the original file. - * @return Return true on success, false if any error occurs. + * @param filePath Indicates the path of the target file. + * @param content Indicates the std::string object to write. + * @param truncated Indicates whether to truncate the original file. + * @return Returns true if the string is written successfully; + * returns false otherwise. */ bool SaveStringToFile(const std::string& filePath, const std::string& content, bool truncated = true); /** * @ingroup FileReadWrite - * @brief Read contents as a string from the file specified by its fd. + * @brief Reads a string from a file specified by its file descriptor (FD). * - * @param fd File descriptor of the specified file. - * @param content Target `std::string` object to store the result. - * @return Return true on success, false if any error occurs. + * @param fd Indicates the FD of the file to read. + * @param content Indicates the std::string object used to hold + * the data read. + * @return Returns true if the string is read successfully; + * returns false otherwise. */ bool LoadStringFromFd(int fd, std::string& content); /** * @ingroup FileReadWrite - * @brief Write contents of a string to the file specified by its fd. + * @brief Writes a string to a file specified by its FD. * - * @param fd File descriptor of the specified file. - * @param content Target `std::string` object to be written to the file. - * @return Return true on success, false if any error occurs. + * @param fd Indicates the FD of the file to write. + * @param content Indicates the std::string object to write. + * @return Returns true if the string is written successfully; + * returns false otherwise. */ bool SaveStringToFd(int fd, const std::string& content); /** * @ingroup FileReadWrite - * @brief Read contents as a vector from the specified file. + * @brief Reads data as a vector from a file. * - * @param filePath Path of the specified file. - * @param content Target `std::vector` object to store the result. - * @return Return true on success, false if any error occurs. + * @param filePath Indicates the path of the target file. + * @param content Indicates the std::vector object used to hold + * the data read. + * @return Returns true if the data is read successfully; + * returns false otherwise. */ bool LoadBufferFromFile(const std::string& filePath, std::vector& content); /** * @ingroup FileReadWrite - * @brief Write contents of a vector to the specified file. + * @brief Writes data of a vector to a file. * - * @param filePath Path of the specified file. - * @param content Target `std::vector` object to be written to the file. - * @return Return true on success, false if any error occurs. + * @param filePath Indicates the path of the target file. + * @param content Indicates the std::vector object to write. + * @return Returns true if the data is written successfully; + * returns false otherwise. */ bool SaveBufferToFile(const std::string& filePath, const std::vector& content, bool truncated = true); /** * @ingroup FileReadWrite - * @brief Check if the specified file exists + * @brief Checks whether a file exists. * - * @param filePath Path of the specified file. - * @return Return true on success, - * false if any error(e.g. Permission Denied) occurs. + * @param filePath Indicates the file to check. + * @return Returns true if the file exists; returns false + * if any error (e.g. Permission Denied) occurs. */ bool FileExists(const std::string& fileName); /** * @ingroup FileReadWrite - * @brief Check if the file contains specified contents in string. + * @brief Checks whether a file contains the specified string. * - * @param fileName Path of the specified file. - * @param subStr Specified `std::string` object - * @param caseSensitive Specify if case-sensitive - * @return Return true if the file contains the specified string, - * false if any error occurs. + * @param fileName Indicates the path of the target file. + * @param subStr Indicates the std::string object to check. + * @param caseSensitive Indicates whether the string is case-sensitive. + * @return Returns true if the file contains the specified string; + * returns false otherwise. */ bool StringExistsInFile(const std::string& fileName, const std::string& subStr, bool caseSensitive = true); /** * @ingroup FileReadWrite - * @brief Get amount of the specified string in the file. + * @brief Obtains the number of occurrences of the specified string in a file. + * - * @param fileName Path of the specified file. - * @param subStr Specified `std::string` object - * @param caseSensitive Specify if case-sensitive - * @return Return the amount, return 0 if `subStr` is null. + * @param fileName Indicates the path of the target file. + * @param subStr Indicates the std::string object to search. + * @param caseSensitive Indicates whether the string is case-sensitive. + * @return Returns the number of occurrences of the string in the file; + * returns 0 if subStr is null. */ int CountStrInFile(const std::string& fileName, const std::string& subStr, bool caseSensitive = true); } diff --git a/base/include/mapped_file.h b/base/include/mapped_file.h index 0ccca64..393107d 100644 --- a/base/include/mapped_file.h +++ b/base/include/mapped_file.h @@ -16,7 +16,7 @@ /** * @file mapped_file.h * - * @brief Provide classes for memory-mapped file implemented in c_utils. + * @brief Provides classes for memory-mapped files implemented in c_utils. */ #ifndef UTILS_BASE_MAPPED_FILE_H diff --git a/base/include/safe_block_queue.h b/base/include/safe_block_queue.h index 80f0dbc..9ea21e6 100644 --- a/base/include/safe_block_queue.h +++ b/base/include/safe_block_queue.h @@ -16,9 +16,9 @@ /** * @file safe_block_queue.h * - * The file contains interfaces of Thread-safe block queues in c_utils. - * Includes the SafeBlockQueue class, and the SafeBlockQueueTracking class - * for trackable tasks. + * Provides interfaces for thread-safe blocking queues in c_utils. + * The file includes the SafeBlockQueue class and + * the SafeBlockQueueTracking class for trackable tasks. */ #ifndef UTILS_BASE_BLOCK_QUEUE_H @@ -33,9 +33,10 @@ namespace OHOS { /** - * @brief Thread-safe blocking queues. + * @brief Provides interfaces for thread-safe blocking queues. * - * Provides blocking and non-blocking push and pop interfaces. + * The interfaces can be used to perform blocking and non-blocking push and + * pop operations on queues. */ template class SafeBlockQueue { @@ -45,41 +46,43 @@ public: } /** - * @brief Insert an element at the end of the queue (blocking). + * @brief Inserts an element at the end of this queue in blocking mode. * - * When the queue is full, the thread of the push operation will be blocked. - * When the queue is not full, the push operation can be executed - * and wakes up one of the waiting threads. + * If the queue is full, the thread of the push operation will be blocked + * until the queue has space. + * If the queue is not full, the push operation can be performed and one of the + * pop threads (blocked when the queue is empty) is woken up. * - * @param elem Enqueue data. + * @param elem Indicates the element to insert. */ virtual void Push(T const& elem) { std::unique_lock lock(mutexLock_); while (queueT_.size() >= maxSize_) { - // queue full , waiting for jobs to be taken + // If the queue is full, wait for jobs to be taken. cvNotFull_.wait(lock, [&]() { return (queueT_.size() < maxSize_); }); } - // here means not full we can push in + // Insert the element into the queue if the queue is not full. queueT_.push(elem); cvNotEmpty_.notify_one(); } /** - * @brief Get the first element of the queue (blocking). + * @brief Removes the first element from this queue in blocking mode. * - * When the queue is empty, the thread of the pop operation will be blocked. - * When the queue is not empty, the pop operation can be executed - * and wakes up one of the waiting threads. Then return the first element - * of the queue. + * If the queue is empty, the thread of the pop operation will be blocked + * until the queue has elements. + * If the queue is not empty, the pop operation can be performed, the first + * element of the queue is returned, and one of the push threads (blocked + * when the queue is full) is woken up. */ T Pop() { std::unique_lock lock(mutexLock_); while (queueT_.empty()) { - // queue empty, waiting for tasks to be Push + // If the queue is empty, wait for elements to be pushed in. cvNotEmpty_.wait(lock, [&] { return !queueT_.empty(); }); } @@ -90,14 +93,14 @@ public: } /** - * @brief Insert an element at the end of queue (Non-blocking). + * @brief Inserts an element at the end of this queue in non-blocking mode. * - * When the queue is full, the thread of the push operation - * will directly return false. - * When the queue is not full, the push operation can be executed - * and wakes up one of the waiting threads, and return true. + * If the queue is full, false is returned directly. + * If the queue is not full, the push operation can be performed, one of the + * pop threads (blocked when the queue is empty) is woken up, and true + * is returned. * - * @param elem Enqueue data. + * @param elem Indicates the element to insert. */ virtual bool PushNoWait(T const& elem) { @@ -105,21 +108,21 @@ public: if (queueT_.size() >= maxSize_) { return false; } - // here means not full we can push in + // Insert the element if the queue is not full. queueT_.push(elem); cvNotEmpty_.notify_one(); return true; } /** - * @brief Get the first elements of the queue (Non-blocking). + * @brief Removes the first element from this queue in non-blocking mode. * - * When the queue is empty, the thread of the pop operation - * will directly return false. - * When the queue is not empty, the pop operation can be executed - * and wakes up one of the waiting threads, and return true. + * If the queue is empty, false is returned directly. + * If the queue is not empty, the pop operation can be performed, one of the + * push threads (blocked when the queue is full) is woken up, and true + * is returned. * - * @param outtask data of pop. + * @param outtask Indicates the data of the pop operation. */ bool PopNotWait(T& outtask) { @@ -156,7 +159,7 @@ public: virtual ~SafeBlockQueue() {} protected: - unsigned long maxSize_; // capacity of queue + unsigned long maxSize_; // Capacity of the queue std::mutex mutexLock_; std::condition_variable cvNotEmpty_; std::condition_variable cvNotFull_; @@ -164,8 +167,9 @@ protected: }; /** - * @brief A thread-safe blocking queue that inherits SafeBlockQueue - * and tracks the number of outstanding tasks. + * @brief Provides interfaces for operating the thread-safe blocking queues + * and tracking the number of pending tasks. + * This class inherits from SafeBlockQueue. */ template class SafeBlockQueueTracking : public SafeBlockQueue { @@ -178,34 +182,35 @@ public: virtual ~SafeBlockQueueTracking() {} /** - * @brief Insert an element at the end of queue (blocking). + * @brief Inserts an element at the end of this queue in blocking mode. * - * When the queue is full, the thread of the push operation will be blocked. - * When the queue is not full, the push operation can be executed - * and wakes up one of the waiting threads. + * If the queue is full, the thread of the push operation will be blocked + * until the queue has space. + * If the queue is not full, the push operation can be performed and one of the + * pop threads (blocked when the queue is empty) is woken up. */ virtual void Push(T const& elem) { unfinishedTaskCount_++; std::unique_lock lock(mutexLock_); while (queueT_.size() >= maxSize_) { - // queue full , waiting for jobs to be taken + // If the queue is full, wait for jobs to be taken. cvNotFull_.wait(lock, [&]() { return (queueT_.size() < maxSize_); }); } - // here means not full we can push in + // If the queue is not full, insert the element. queueT_.push(elem); cvNotEmpty_.notify_one(); } /** - * @brief Insert an element at the end of queue (Non-blocking). + * @brief Inserts an element at the end of this queue in non-blocking mode. * - * When the queue is full, the thread of the push operation - * will directly return false. - * When the queue is not full, the push operation can be executed - * and wakes up one of the waiting threads, and return true. + * If the queue is full, false is returned directly. + * If the queue is not full, the push operation can be performed, + * one of the pop threads (blocked when the queue is empty) is woken up, + * and true is returned. */ virtual bool PushNoWait(T const& elem) { @@ -213,7 +218,7 @@ public: if (queueT_.size() >= maxSize_) { return false; } - // here means not full we can push in + // Insert the element if the queue is not full. queueT_.push(elem); unfinishedTaskCount_++; cvNotEmpty_.notify_one(); @@ -221,14 +226,14 @@ public: } /** - * @brief A response function when a task completes. + * @brief Called to return the result when a task is complete. * - * If the count of unfinished task < 1, return false directly. - * If the count of unfinished task = 1, all threads waiting - * while calling Join() will be woken up; - * the count of unfinished task decrements by 1 and returns true. - * If the count of unfinished task > 1, - * decrements the count by 1 and returns true. + * If the count of unfinished tasks < 1, false is returned directly. + * If the count of unfinished tasks = 1, all the threads blocked + * by calling Join() will be woken up, + * the count of unfinished tasks decrements by 1, and true is returned. + * If the count of unfinished tasks > 1, + * the count of unfinished tasks decrements by 1, and true is returned. */ bool OneTaskDone() { @@ -247,9 +252,9 @@ public: } /** - * @brief Wait for all tasks to complete. + * @brief Waits for all tasks to complete. * - * When anyone of the tasks is not completed, the current thread will be + * If there is any task not completed, the current thread will be * blocked even if it is just woken up. */ void Join() @@ -259,7 +264,7 @@ public: } /** - * @brief Returns the number of unfinished tasks. + * @brief Obtains the number of unfinished tasks. */ int GetUnfinishTaskNum() { diff --git a/base/include/safe_map.h b/base/include/safe_map.h index 4a3fc61..f3c2285 100644 --- a/base/include/safe_map.h +++ b/base/include/safe_map.h @@ -22,7 +22,7 @@ namespace OHOS { /** - * @brief A thread-safe map implementation is provided. + * @brief Provides interfaces for thread-safe map operations. */ template class SafeMap { @@ -51,10 +51,11 @@ public: } /** - * @brief Get the size of the map. + * @brief Obtains the map size. * - * when multithread calling Size() return a tmp status, some threads may - * insert just after Size() call. + * In the multithread scenario, the map size returned is a tmp status, + * because elements may be inserted or removed by other threads after + * Size() is called. */ int Size() { @@ -63,12 +64,14 @@ public: } /** - * @brief Determine whether the map is empty or not. + * @brief Checks whether the map is empty. * - * when multithread calling Empty() return a tmp status, some threads may - * insert just after Empty() call. + * In the multithread scenario, the value returned by Empty() is a + * tmp status, because elements may be inserted or removed by other threads + * after Empty() is called. * - * @return Return true if it is empty, otherwise returns false. + * @return Returns true if the map is empty; + * returns false otherwise. */ bool IsEmpty() { @@ -77,12 +80,12 @@ public: } /** - * @brief Insert a new element into the map. + * @brief Inserts an element to the map. * - * @param key The key to be inserted. - * @param value The value to be inserted. - * @return Return true if the insertion is successful, otherwise returns - * false. + * @param key Indicates the key of the key-value (KV) pair to insert. + * @param value Indicates the value of the KV pair to insert. + * @return Returns true if the KV pair is inserted; returns + * false otherwise. */ bool Insert(const K& key, const V& value) { @@ -92,12 +95,12 @@ public: } /** - * @brief Insert elements into the map. + * @brief Forcibly inserts an element to the map. * - * @param key The key to be inserted. - * @param value The value to be inserted. - * @note Delete and then insert when the key exists, ensuring that the - * final value is inserted. + * @param key Indicates the key of the KV pair to insert. + * @param value Indicates the value of the KV pair to insert. + * @note If the key to insert already exists, delete and then insert + * the KV pair to ensure that the value is inserted. */ void EnsureInsert(const K& key, const V& value) { @@ -113,11 +116,12 @@ public: } /** - * @brief Search for elements in the map. + * @brief Searches for an element in the map. * - * @param Key The key to be found. - * @param value The value corresponding to the found key. - * @return Return true when the key exists, otherwise returns false. + * @param Key Indicates the key to search. + * @param value Indicates the value of the KV pair to search. + * @return Returns true if the KV pair is found; + * returns false otherwise. */ bool Find(const K& key, V& value) { @@ -134,13 +138,13 @@ public: } /** - * @brief Search for elements in the map and replace the `oldValue` - * corresponding to the key with `newValue`. + * @brief Replaces the value of a KV pair. * - * @param Key The key to be found. - * @param oldValue The value corresponding to the found key. - * @param newValue The new value to insert. - * @return Return true when the key exists, otherwise returns false. + * @param Key Indicates the key of the KV pair. + * @param oldValue Indicates the value to be replaced. + * @param newValue Indicates the new value of the KV pair. + * @return Returns true if the key is replaced; + * returns false otherwise. */ bool FindOldAndSetNew(const K& key, V& oldValue, const V& newValue) { @@ -160,9 +164,9 @@ public: } /** - * @brief Delete key-value pairs whose key is key in the map. + * @brief Erases a KV pair. * - * @param Key The key to be deleted. + * @param Key Indicates the key of the KV pair to erase. */ void Erase(const K& key) { @@ -171,7 +175,7 @@ public: } /** - * @brief Delete all key-value pairs stored in the map. + * @brief Deletes all KV pairs from the map. */ void Clear() { @@ -183,10 +187,10 @@ public: using SafeMapCallBack = std::function; /** - * @brief Iterate through the elements in the map. + * @brief Iterates over the elements of the map. * - * @param callback A specific function that performs custom operations on - * each KV key-value pair. + * @param callback Called to perform the custom operations on + * each KV pair. */ void Iterate(const SafeMapCallBack& callback) { diff --git a/base/include/safe_queue.h b/base/include/safe_queue.h index 9c97047..eb30bf4 100644 --- a/base/include/safe_queue.h +++ b/base/include/safe_queue.h @@ -16,10 +16,10 @@ /** * @file safe_queue.h * - * @brief The file contains interfaces of thread-safe queues in c_utils. + * @brief Provides interfaces for thread-safe queue operations in c_utils. * - * The file contains thread-safe abstract class, the SafeQueue - * and SafeStack that override the virtual methods of the abstract class. + * The file contains the thread-safe abstract class, the SafeQueue + * and SafeStack that override the virtual methods of the abstract class. */ #ifndef UTILS_BASE_SAFE_QUEUE_H @@ -31,10 +31,10 @@ namespace OHOS { /** - * @brief An abstract class for thread-safe queues. + * @brief Provides an abstract class for thread-safe queues. * - * Encapsulate std::lock_guard locks on the basis of std::deque, - * so that the interface of the queue becomes thread-safe. + * It encapsulates std::lock_guard locks on the basis of std::deque to + * make the interfaces of the queue thread-safe. */ template class SafeQueueInner { @@ -98,10 +98,10 @@ protected: }; /** - * @brief Thread-safe Queue. + * @brief Provides thread-safe queue operations. * - * Overrides the DoPush and DoPop methods of abstract classes to implement - * the push and pop functionality of the "SafeQueue". + * It overrides the DoPush and DoPop methods of abstract classes + * to implement the push and pop functionality of SafeQueue. */ template class SafeQueue : public SafeQueueInner { @@ -116,8 +116,8 @@ protected: } /** - * @brief Encapsulate the pop_front() of dequeues - * and implement the pop function of queues. + * @brief Encapsulates the pop_front() method + * to implement the pop function of queues. */ bool DoPop(T& pt) override { @@ -132,10 +132,10 @@ protected: }; /** - * @brief Thread-safe Stack. + * @brief Provides thread-safe stack operations. * - * Overrides the DoPush and DoPop methods of abstract classes - * to implement the push and pop functionality of the "SafeStack". + * It overrides the DoPush and DoPop methods of abstract classes + * to implement the push and pop functionality of SafeStack. */ template class SafeStack : public SafeQueueInner { @@ -150,8 +150,8 @@ protected: } /** - * @brief Encapsulate the pop_back() of dequeues - * and implement the pop function of stack. + * @brief Encapsulates the pop_back() method + * to implement the pop function of stack. */ bool DoPop(T& pt) override { diff --git a/base/include/semaphore_ex.h b/base/include/semaphore_ex.h index 5c4ca67..f3e04c7 100644 --- a/base/include/semaphore_ex.h +++ b/base/include/semaphore_ex.h @@ -16,14 +16,14 @@ /** * @file semaphore_ex.h * - * @brief This file contains interfaces of Semaphore in c_utils, + * @brief Provides interfaces of semaphores in c_utils, * including nameless and named semaphores. * - * The semaphore is an atomic counter, which can act as a lock, - * to achieve mutual exclusion, synchronization and other functions; - * Used in a multithreaded environment, it is possible to ensure that - * a critical pieces of code is not called concurrently or maximum number - * of threads entering the code section is restricted. + * A semaphore is an atomic counter, which can act as a lock + * to achieve mutual exclusion, synchronization, and other functions. + * Used in a multithreaded environment, it prevents concurrent + * calling of a critical piece of code or restricts the maximum number + * of threads entering the code section. */ #ifndef SEMAPHORE_EX_H @@ -39,214 +39,48 @@ #include // timespec since c11 namespace OHOS { - -const int INVALID_SEMA_VALUE = -1; - -/** - * @brief NamedSemaphore. - * - * The only difference between the NamedSemaphore and the Semaphore - * lies in the form of creation and destruction. - * Generally, the name of the specified semaphore is explicitly specified - * at the time of creation, and can be accessed directly by name, - * so it can be used in any process/thread that knows its name. - * The characteristic of the NamedSemaphore is that they are saved in a file, - * so it is necessary to close the semaphore at the end like closing the file. - */ -class NamedSemaphore : public NoCopyable { -public: - -/** - * @brief Construct a NamedSemaphore object with a default name, - * and initial value of the semaphore. - * - * The constructor only creates a NamedSemaphore object and does not - * call sem_open(), so you need to call Create() to create semaphores - * after construction. - * - * @param size the initial value of semaphore. - */ - explicit NamedSemaphore(size_t); - -/** - * @brief Construct a NamedSemaphore object, - * specify the name and initial value of the semaphore. - * - * The constructor only creates a NamedSemaphore object and does not - * call sem_open(), so you need to call Create() to create semaphores - * after construction. - * - * @param name the name of NamedSemaphore; NamedSemaphore objects constructed - * by constructors that do not specify a name are assigned - * a unique name by default. - * @param size the initial value of semaphore. - */ - NamedSemaphore(const std::string&, size_t); - -/** - * @brief Destroy a NamedSemaphore object. - */ - ~NamedSemaphore() override; - -/** - * @brief Create and initialize a named semaphore. - * - * When a Namedsemaphore is created, a sem.xxx file is generated under - * /dev/shm, and all processes/threads that open the semaphore - * (including the processes/threads that created it) increment the reference - * counter for that file managed by the kernel. - * - * @return Success returns ture, failure returns false. - */ - bool Create(); - -/** - * @brief Remove the semaphore from the system. - * - * When Unlink() is called, the sem.xxx file under /dev/shm rather than - * the semaphore itself will be deleted immediately, and all processes that - * have opened the semaphore can still use it normally (because the semaphore - * file that has been opened is in memory), even if Unlink() is called - * immediately after opening the file, Wait(), Post() can also operate - * normally on the semaphore. - * Each semaphore has a reference counter that records the number of times - * it has been opened, and when the reference counter is 0, - * the named semaphore can be deleted from the file system by Unlink(). - * That is, the kernel does not actually delete the semaphore until - * all processes that open the semaphore have closed the semaphore - * (the last sem_close call completes). - * - * @return Success returns ture, failure returns false. - */ - bool Unlink(); - -/** - * @brief Open a Namedsemaphore file that has already been created. - * - * @return Success returns ture, failure returns false. - */ - bool Open(); - -/** - * @brief Turn off the NamedSemaphore. - * - * Turn off the semaphore and do not remove it from the system. - * - * @return Success returns ture, failure returns false. - */ - bool Close(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1). - * - * If the current count value is 0, the call blocks util another call of Post() - * makes the count greater than 0. - * - * @return Success returns 0; Failure returns -1, the semaphore will not be - * changed by the interface, and errno is set to indicate a specific error. - */ - bool Wait(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1); - * Non-blocking version. - * - * The non-blocking version of Wait() returns an error directly - * when the current semaphore = 0, not blocking. - * - * @return Success returns 0; Failure returns -1, the signal will - * not be changed by the interface, - * and errno is set to indicate a specific error. - */ - bool TryWait(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1); - * Specifies the blocking time version. - * - * The version of Wait() that specifies the blocking time, - * if the value of the semaphore is great than 0, - * the -1 operation is performed, and the function returns immediately; - * When the -1 operation cannot be executed, the call will block - * (specify the blocking time). - * - * @param ts Specifies the blocking time of the call. - * @return Success returns 0; Failure returns -1, the semaphore will - * not be changed by the interface, - * and errno is set to indicate a specific error. - */ - bool TimedWait(const struct timespec& ts); - -/** - * @brief Interface for releasing semaphore (the count of semaphore +1). - * - * If the value of the semaphore thus becomes greater than 0, - * another process/thread that is blocked due to the sem_wait of the call - * will be woken up and will lock the semaphore. - * - * @return Success returns 0; Failure returns -1, the semaphore will not be - * changed by the interface, and errno is set to indicate a specific error. - */ - bool Post(); - -/** - * @brief Get the value of the semaphore. - * - * @return The value of the semaphore is successfully returned; - * Failure returns INVALID_SEMA_VALUE, which is -1. - */ - int GetValue() const; - -private: - std::string name_; // The name of the NamedSemaphore object - int maxCount_; // The initial value of the NamedSemaphore object - void* sema_; // The pointer to the sem_t structure, which is essentially a long integer. - bool named_; // The flag of a Namedsemaphore that is false when no named semaphore name is specified. - -}; - /** - * @brief Semaphore. This class is a counter to implement functions such as - * mutual exclusion between processes/threads, synchronization, etc. + * @brief Provides interfaces for operating semaphores. * + * A semaphore is a counter used to implement functions, such as + * mutual exclusion between processes/threads, synchronization, and more. * The difference between nameless semaphores and named semaphores lies * in the form of creation and destruction. - * The semaphore exists only in memory, requiring that the process/thread + * Semaphores exist only in memory. The process/thread * using the semaphore must access the memory where the semaphore is located. * Therefore, the nameless semaphore can only be in the thread of * the same process, or threads in different processes that have mapped - * the same memory to their address space, that is, the nameless semaphore + * the same memory to their address space, that is, the nameless semaphores * can only be accessed through shared memory. */ class Semaphore : public NoCopyable { public: /** - * @brief Construct a semaphore object. + * @brief A constructor used to create a semaphore object. * - * @param Value The initial value of the semaphore object. + * @param Value Indicates the initial value of the semaphore object. */ explicit Semaphore(int value = 1) : count_(value) {} /** - * @brief Acquire semaphore operation, i.e. semaphore -1. + * @brief Acquires the semaphore. * - * When the semaphore is >= 0 after decrement, the current thread continues. - * When semaphore is < 0 after decrement, the current thread blocks. + * If the current semaphore count >= 0, the current thread continues. + * If the current semaphore count < 0, the current thread will be blocked. */ void Wait(); /** - * @brief Release semaphore operation, i.e. semaphore +1. + * @brief Releases the semaphore. * - * When the semaphore is > 0 after increment, it means that - * there is no blocked thread. - * When the semaphore is <= 0 after increment, it means that there are still + * If the current semaphore count > 0, there is no blocked thread. + * If the current semaphore count <= 0, there are still * blocked threads. Then this method will wake one of them up. */ void Post(); private: - int count_; // The initial value of the Semaphore object + int count_; // Initial value of the semaphore object. std::mutex mutex_; std::condition_variable cv_; }; diff --git a/base/include/thread_ex.h b/base/include/thread_ex.h index 7482134..242b978 100644 --- a/base/include/thread_ex.h +++ b/base/include/thread_ex.h @@ -16,7 +16,7 @@ /** * @file thread_ex.h * - * @brief The file contains interfaces of the Thread class + * @brief Provides interfaces of the Thread class * implemented in c_utils. */ @@ -47,77 +47,81 @@ constexpr int INVALID_PTHREAD_T = -1; constexpr int MAX_THREAD_NAME_LEN = 15; /** - * @brief A thread class provided by c_utils, include functions such as - * creating threads and getting thread ID. + * @brief Provides interfaces for creating a thread + * and obtaining a thread ID. */ class Thread { public: /** - * @brief Construct a Thread object, but does not start the thread. + * @brief A constructor used to create a Thread object, without + * starting the thread. */ Thread(); virtual ~Thread(); /** - * @brief Create and start a child thread, and execute Run() in a loop. - * Loop stops when Run() returns false or notifies to exit by - * `NotifyExitSync()` or `NotifyExitAsync()` from another thread. + * @brief Creates and starts a child thread, and executes + * Run() in a loop. + * The loop stops when Run() returns false or it is notified + * to exit by `NotifyExitSync()` or `NotifyExitAsync()` from another thread. * - * @param name The thread name. - * @param priority Thread priority. - * @param stack The size of the thread stack. - * @return Return OK if the call is successful; - * return INVALID_OPERATION when the thread already exists; - * return UNKNOWN_ERROR when thread creation fails. - * @see NotifyExitSync() NotifyExitAsync() + * @param name Indicates the name of the thread. + * @param priority Indicates the thread priority. + * @param stack Indicates the size of the thread stack. + * @return Returns OK if the call is successful; + * returns INVALID_OPERATION if the thread already exists; + * returns UNKNOWN_ERROR if the thread creation fails. + * @see {@link NotifyExitSync()} or {@link NotifyExitAsync()} */ ThreadStatus Start(const std::string& name, int32_t priority = THREAD_PROI_NORMAL, size_t stack = 0); /** - * @brief Synchronously notify this Thread object to exit. + * @brief Synchronously instructs this Thread object to exit. * - * The current thread is blocked, waiting for the child thread to finish. + * This method can be called only by another thread to instruct this + * Thread object to exit. The calling thread will be blocked until this + * Thread object exits. */ ThreadStatus NotifyExitSync(); /** - * @brief Asynchronously notify this Thread object to exit. + * @brief Asynchronously instructs this Thread object to exit. * - * That is, whether the child thread exits does not block - * the current thread. Notifies the child thread to stop - * and the current thread to continue running. + * This method can be called only by another thread to instruct this + * Thread object to exit. However, the calling thread will not be blocked + * when this Thread object exits. */ virtual void NotifyExitAsync(); /** - * @brief Determine whether the thread is ready. + * @brief Checks whether the thread is ready. */ virtual bool ReadyToWork(); /** - * @brief Get the flag of the thread exitPending. + * @brief Checks whether there is any thread waiting for exit. * - * If the flag is true, other waiting threads who have called - * `NotifyExitSync()` are woken up when the current thread - * finishes running and exits. + * If true is returned, the waiting threads who have called + * `NotifyExitSync()` will be woken up when the current thread finishes + * running and exits. * - * @return Returns true, indicating that another thread may be - * blocking to wait for the current thread to complete; - * Otherwise return false. + * @return Returns true if there is any thread that is + * blocked to wait for the current thread to exit. + * Returns false otherwise. */ bool IsExitPending() const; /** - * @brief Determine whether the thread is running. + * @brief Checks whether the thread is running. * - * @return Return true if the thread is running, - * otherwise, return false. + * @return Returns true if the thread is running; + * returns false otherwise. */ bool IsRunning() const; /** - * @brief Get the thread ID. + * @brief Obtains the thread ID. */ pthread_t GetThread() const { return thread_; } @@ -135,7 +139,7 @@ private: std::condition_variable cvThreadExited_; ThreadStatus status_; volatile bool exitPending_; - volatile bool running_; // flag of thread runing + volatile bool running_; // flag of thread running }; } // namespace OHOS diff --git a/base/include/thread_pool.h b/base/include/thread_pool.h index 1559097..f522724 100644 --- a/base/include/thread_pool.h +++ b/base/include/thread_pool.h @@ -27,78 +27,80 @@ namespace OHOS { /** - * @brief Give a thread-safe thread pool. + * @brief Provides interfaces for thread-safe thread pool operations. * - * The thread-safe is for threadpool itself not for the threads in pool. A task - * queue and a thread group are under control. Users add tasks to task queue. - * The thread group will execute the tasks in task queue. + * The thread-safe is for the thread pool, but not for the threads in the pool. + * A task queue and a thread group are under control. Users add tasks to the + * task queue, and the thread group executes the tasks in the task queue. */ class ThreadPool : public NoCopyable { public: typedef std::function Task; /** - * @brief Construct ThreadPool and name the threads in pool. + * @brief Creates a thread pool and names the threads in the pool. * - * @param name it will be set as a part the real name of threads in pool. - * The real name of threads in pool will be like: name + No. The thread - * name is a meaningful C language string, whose length is restricted to - * 16 characters, including the terminating null byte ('\0'). Please pay - * attention to the length of name here. For example, if the number of - * threads in pool is less than 10, the maximum length of name is 14. + * @param name Indicates the prefix of the names of the threads in pool. + * The names of threads in the pool are in the name + No format. + * The thread name is a meaningful C language string, whose length is + * restricted to 16 characters including the terminating null byte ('\0'). + * Pay attention to the name length when setting this parameter. + * For example, if the number of threads in the pool is less than 10, + * the name length cannot exceed 14 characters. */ explicit ThreadPool(const std::string &name = std::string()); ~ThreadPool() override; /** - * @brief Start a given number(threadsNum) of threads, which will execute - * the tasks in task queue. + * @brief Starts a given number of threads, which will execute + * the tasks in a task queue. * - * @param threadsNum A given number of threads to start. + * @param threadsNum Indicates the number of threads to start. */ uint32_t Start(int threadsNum); /** - * @brief Stop ThreadPool and wait all threads in pool to stop. + * @brief Stops the thread pool. */ void Stop(); /** - * @brief Add a Task to task queue. + * @brief Adds a task to the task queue. * - * If Start() has never been called, the Task will be executed immediately. + * If Start() has never been called, the task will be executed + * immediately. * - * @param f A Task to be added to task queue. + * @param f Indicates the task to add. */ void AddTask(const Task& f); /** - * @brief Set the maximum amount of tasks in task queue. + * @brief Sets the maximum number of tasks in the task queue. * - * @param maxSize The maximum amount of tasks in task queue. + * @param maxSize Indicates the maximum number of tasks to set. */ void SetMaxTaskNum(size_t maxSize) { maxTaskNum_ = maxSize; } // for testability /** - * @brief Get the maximum amount of tasks in task queue. + * @brief Obtains the maximum number of tasks in the task queue. */ size_t GetMaxTaskNum() const { return maxTaskNum_; } /** - * @brief Get the current amount of tasks in task queue. + * @brief Obtains the number of tasks in the task queue. */ size_t GetCurTaskNum(); /** - * @brief Get the current amount of threads in pool. + * @brief Obtains the number of threads in the pool. */ size_t GetThreadsNum() const { return threads_.size(); } /** - * @brief Get the name of ThreadPool. + * @brief Obtains the name of the thread pool. */ std::string GetName() const { return myName_; } private: - // tasks in the queue reach the maximum set by maxQueueSize, means thread pool is full load. + // If the number of tasks in the queue reaches the maximum set by maxQueueSize, the thread pool is full load. bool Overloaded() const; void WorkInThread(); // main function in each thread. - Task ScheduleTask(); // fetch a task from the queue and execute + Task ScheduleTask(); // fetch a task from the queue and execute it private: std::string myName_; -- Gitee