1、程序簡介
該程序是基于OpenHarmony標準系統的C++公共基礎類庫的線程處理:Sempahore。
本案例完成如下工作:
(1)無名信號量使用方法
定義1個無名信號量,1個供無名信號量管理的公共資源變量;
創建5個線程,每個線程做5次for循環,for循環的內容是獲取無名信號量,并修改公共資源變量;
(2)有名信號量使用方法
定義1個有名信號量,1個供有名信號量管理的公共資源變量;
創建1個線程A,通過Open獲取信號量,做5次for循環,for循環的內容是通過Wait獲取有名信號量,如果獲取成功則修改公共資源變量(即累加1),最后釋放信號量;
創建1個線程B,通過Open獲取信號量,做5次for循環,for循環的內容是通過TryWait獲取有名信號量,如果獲取成功則修改公共資源變量(即累加10),最后釋放信號量;
創建1個線程C,通過Open獲取信號量,做5次for循環,for循環的內容是通過TimedWait獲取有名信號量,如果獲取成功則修改公共資源變量(即累加100),最后釋放信號量;
2、基礎知識
C++公共基礎類庫為標準系統提供了一些常用的C++開發工具類,包括:
文件、路徑、字符串相關操作的能力增強接口
讀寫鎖、信號量、定時器、線程增強及線程池等接口
安全數據容器、數據序列化等接口
各子系統的錯誤碼相關定義
2.1、添加C++公共基礎類庫依賴
修改需調用模塊的BUILD.gn,在external_deps或deps中添加如下:
ohos_shared_library("xxxxx") { ... external_deps = [ ... # 動態庫依賴(可選) "c_utils:utils", # 靜態庫依賴(可選) "c_utils:utilsbase", # Rust動態庫依賴(可選) "c_utils:utils_rust", ] ...}
一般而言,我們只需要填寫"c_utils:utils"即可。
2.2、Semaphore頭文件
C++公共基礎類庫的Semaphore頭文件在://commonlibrary/c_utils/base/include/semaphore_ex.h
可在源代碼中添加如下:
#include
OpenHarmony信號量根據種類可以分為有名信號量和無名信號量,所以命令空間如下:
(1)無名信號量命名空間
OHOS::Semaphore
(2)有名信號量命名空間
OHOS::NamedSemaphore
2.3、OHOS::Samaphore接口說明
Semaphore為無名信號量。
2.3.1、Samaphore
構造函數, 構造一個Samaphore對象。
Semaphore(int value = 1);
參數說明:
參數名稱 | 類型 | 參數說明 |
---|---|---|
value | int | 信號量當前資源數量 |
2.3.2、~Semaphore
析構函數。
~Semaphore();
2.3.3、Wait
等待/獲取信號量(即信號量 -1)。
void Wait();
2.3.4、Post
釋放信號量(即信號量 +1)。
void Post();
2.4、OHOS::NamedSemaphore接口說明
NamedSemaphore為有名信號量。
2.4.1、NamedSemaphore
構造函數, 構造NamedSemaphore對象。
NamedSemaphore(size_t size)NamedSemaphore(const std::string& name, size_t size)
參數說明:
參數名稱 | 類型 | 參數說明 |
---|---|---|
name | std::string | 信號量名稱 |
size | size_t | 信號量有效資源數量 |
2.4.2、~NamedSemaphore
析構函數。
~NamedSemaphore();
2.4.3、Create
創建并初始化有名信號量。
bool Create();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.4、Unlink
將有名信號量文件從系統中刪除。
bool Unlink();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.5、Open
打開一個已經創建的有名信號量文件。
bool Open();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.6、Close
關閉有名信號量。
bool Close();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.7、Wait
等待/獲取信號量(信號量 -1)。
bool Wait();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.8、TryWait
等待/獲取信號量(信號量 -1)的接口;非阻塞版。
bool TryWait();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.9、TimedWait
等待/獲取信號量(信號量 -1);指定阻塞時間版。
bool TimedWait(const struct timespec& ts);
參數說明:
參數名稱 | 類型 | 參數說明 |
---|---|---|
ts | struct timespec | 絕對時間。注意:ts是utc時間,不是相對時間。 |
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.10、Post
釋放信號量(信號量 +1)。
bool Post();
返回值說明:
類型 | 返回值說明 |
---|---|
bool | true表示成功,false表示失敗 |
2.4.10、GetValue
獲取信號的值。
int GetValue() const;
返回值說明:
類型 | 返回值說明 |
---|---|
int | 返回當前信號量的值 |
3、程序解析
3.1、創建編譯引導
在//vendor/lockzhiner/rk3568/samples/BUILD.gn文件添加一行編譯引導語句。
import("http://build/ohos.gni")
group("samples") { deps = [ "a24_utils_semaphore:utils_semaphore", # 添加該行 ]}
"a24_utils_semaphore:utils_semaphore",該行語句表示引入參與編譯。
3.2、創建編譯項目
創建a24_utils_semaphore目錄,并添加如下文件:
a24_utils_semaphore├── utils_name_semaphore.cpp # 有名信號量案例├── utils_noname_semaphore.cpp # 無名信號量案例├── BUILD.gn # GN文件
3.3、創建BUILD.gn
編輯BUILD.gn文件。
添加2個可執行程序,分別是:
utils_noname_semaphore:無名信號量使用案例
utils_name_semaphore:有名信號量使用案例
import("http://build/ohos.gni")
ohos_executable("utils_noname_semaphore") { sources = [ "utils_noname_semaphore.cpp" ] include_dirs = [ "http://commonlibrary/c_utils/base/include", "http://commonlibrary/c_utils/base:utils", "http://third_party/googletest:gtest_main", "http://third_party/googletest/googletest/include", ] external_deps = [ "c_utils:utils" ] part_name = "product_rk3568" install_enable = true}
ohos_executable("utils_name_semaphore") { sources = [ "utils_name_semaphore.cpp" ] include_dirs = [ "http://commonlibrary/c_utils/base/include", "http://commonlibrary/c_utils/base:utils", "http://third_party/googletest:gtest_main", "http://third_party/googletest/googletest/include", ] external_deps = [ "c_utils:utils" ] part_name = "product_rk3568" install_enable = true}
group("utils_semaphore") { deps = [ ":utils_noname_semaphore", ":utils_name_semaphore", ]}
注意:
(1)BUILD.gn中所有的TAB鍵必須轉化為空格,否則會報錯。如果自己不知道如何規范化,可以:
# 安裝gn工具sudo apt-get install ninja-buildsudo apt install generate-ninja# 規范化BUILD.gngn format BUILD.gn
3.4、無名信號量使用案例
3.4.1、添加信號量頭文件
#include
3.4.2、創建無名信號量以及公共資源變量
static int m_count = 0; // 公共資源變量static OHOS::Semaphore m_sem(1); // 無名信號量
3.4.3、創建線程池
OHOS::ThreadPoolthreads("noname_semaphore_threads");
3.4.4、設置線程池
OHOS::ThreadPool threads("noname_semaphore_threads");
3.4.5、啟動線程
for (int i = 0; i < threads_start; i++) { string str_name = "thread_" + to_string(i); auto task = std::bind(func, str_name); threads.AddTask(task); sleep(1);}
3.4.6、編寫子線程代碼
循環5次,每次循環調用信號量Wait()等待獲取信號量。如果獲取信號量后,將公共資源變量累加,調用信號量Post()釋放信號量。
void func(const string &name){ for (int i = 0; i < 5; i++) { cout << name << ": Sema Wait..." << endl; m_sem.Wait(); cout << name << ": Sema Wait Successful" << endl; m_count += 1; m_sem.Post(); cout << name << ": Sema Post" << endl; sleep(1); }}
3.5、有名信號量使用案例
3.5.1、添加信號量頭文件
#include
3.5.2、創建有名信號量
首先定義有名信號量,然后通過Create()創建全局有名信號量。
int main(int argc, char **argv){ OHOS::NamedSemaphore sem(STRING_NAME_SEMAPHORE, 1); ...... if (!sem.Create()) { cout << "NamedSemaphore.Create() failed\n"; return -1; } ......}
3.5.3、創建線程池
通過OHOS::ThreadPool定義線程池,調用SetMaxTaskNum()設置線程池最大線程數,并調用Start()設置當前啟動多少個線程。
int main(int argc, char **argv){ OHOS::ThreadPool threads("name_semaphore_threads"); int threads_start = 3; ...... threads.SetMaxTaskNum(128); threads.Start(threads_start); ......}
3.5.4、啟動子線程A、B和C
int main(int argc, char **argv){ ...... // 啟動線程A str_name = "thread_a"; auto task_a = std::bind(funcA, str_name); threads.AddTask(task_a); // 啟動線程B str_name = "thread_b"; auto task_b = std::bind(funcB, str_name); threads.AddTask(task_b);
// 啟動線程A str_name = "thread_c"; auto task_c = std::bind(funcC, str_name); threads.AddTask(task_c); threads.Stop(); cout << "threads stop" << endl; return 0;}
3.5.5、編寫子線程A
首先定義有名信號量,信號量數目可以隨意設置。
其次,通過Open()打開有名信號量,可以與main()的有名信號量共享同一個信號量。
最后,通過Wait()和Post()來獲取釋放信號量。
static void funcA(const string &name){ OHOS::NamedSemaphore sem(STRING_NAME_SEMAPHORE, 1);
cout << get_curtime() << ", " << name << ": start\n";
// 打開一個已經創建的有名信號量文件 if (!sem.Open()) { cout << get_curtime() << ", " << name << ": sema open failed" << endl; return; } for (int i = 0; i < 5; i++) { cout << get_curtime() << ", " << name << ": sema wait..." << endl; sem.Wait(); cout << get_curtime() << ", " << name << ": sema wait success" << endl; m_count += 1; usleep(1000 * 1000 * 1); cout << get_curtime() << ", " << name << ": sema count = " << m_count << endl; sem.Post(); cout << get_curtime() << ", " << name << ": sema post and sleep 1 sec" << endl; sleep(1); }
cout << get_curtime() << ", " << name << ": end" << endl;}
3.5.6、編寫子線程B
首先定義有名信號量,信號量數目可以隨意設置。
其次,通過Open()打開有名信號量,可以與main()的有名信號量共享同一個信號量。
最后,通過TryWait()和Post()來獲取釋放信號量。
static void funcB(const string &name){ OHOS::NamedSemaphore sem(STRING_NAME_SEMAPHORE, 1);
cout << get_curtime() << ", " << name << ": start\n"; // 打開一個已經創建的有名信號量文件 if (!sem.Open()) { cout << get_curtime() << ", " << name << ": sema open failed" << endl; return; }
for (int i = 0; i < 5; i++) { cout << get_curtime() << ", " << name << ": sema trywait..." << endl; if (sem.TryWait()) { cout << get_curtime() << ", " << name << ": sema trywait success" << endl; m_count += 10; usleep(1000 * 1000 * 1); cout << get_curtime() << ", " << name << ": sema count = " << m_count << endl; sem.Post(); cout << get_curtime() << ", " << name << ": sema post and sleep 1 sec" << endl; } else { cout << get_curtime() << ", " << name << ": sema tryWait failed and sleep 1 sec" << endl; } sleep(1); }
cout << get_curtime() << ", " << name << ": end" << endl;}
3.5.7、編寫子線程C
首先定義有名信號量,信號量數目可以隨意設置。
其次,通過Open()打開有名信號量,可以與main()的有名信號量共享同一個信號量。
最后,通過TimedWait()和Post()來獲取釋放信號量。
static void funcC(const string &name){ OHOS::NamedSemaphore sem(STRING_NAME_SEMAPHORE, 1); struct timespec ts;
cout << get_curtime() << ", " << name << ": start\n";
// 打開一個已經創建的有名信號量文件 if (!sem.Open()) { cout << get_curtime() << ", " << name << ": sema open failed" << endl; return; } for (int i = 0; i < 5; i++) { clock_gettime(CLOCK_REALTIME, &ts); // 超時等待時間,1秒 ts.tv_sec += 1; cout << get_curtime() << ", " << name << ": sema timedwait 1 sec..." << endl; if (sem.TimedWait(ts)) { cout << get_curtime() << ", " << name << ": sema timedwait success" << endl; m_count += 100; usleep(1000 * 100); cout << get_curtime() << ", " << name << ": sema count = " << m_count << endl; sem.Post(); cout << get_curtime() << ", " << name << ": sema post" << endl; } else { cout << get_curtime() << ", " << name << ": sema timedwait failed and sleep 1 sec" << endl; sleep(1); } }
cout << get_curtime() << ", " << name << ": end" << endl;
}
4、編譯步驟
進入OpenHarmony編譯環境,運行如下命令:
hb build -f
將鏡像燒錄到開發板中。
5、運行結果
5.1、無名信號量
運行結果如下:
# utils_noname_semaphorethread_0: Sema Wait...thread_0: Sema Wait Successfulthread_0: Sema Postthread_1: Sema Wait...thread_1: Sema Wait Successfulthread_1: Sema Postthread_0: Sema Wait...thread_0: Sema Wait Successfulthread_0: Sema Postthread_2: Sema Wait...thread_2: Sema Wait Successfulthread_2: Sema Postthread_0: Sema Wait...thread_0: Sema Wait Successfulthread_0: Sema Postthread_1: Sema Wait...thread_1: Sema Wait Successfulthread_1: Sema Postthread_3: Sema Wait...thread_3: Sema Wait Successfulthread_3: Sema Postthread_2: Sema Wait...thread_0: Sema Wait Successfulthread_2: Sema Wait...thread_2: Sema Postthread_1: Sema Wait...thread_0: Sema Wait Successfulthread_0: Sema Postthread_1: Sema Wait Successfulthread_1: Sema Postthread_4: Sema Wait...thread_4: Sema Wait Successfulthread_4: Sema Postthread_3: Sema Wait...thread_3: Sema Wait Successfulthread_3: Sema Postthread_2: Sema Wait...thread_2: Sema Wait Successfulthread_2: Sema Postthread_0: Sema Wait...thread_0: Sema Wait Successfulthread_0: Sema Postthread_1: Sema Wait...thread_1: Sema Wait Successfulthread_1: Sema Postthread_4: Sema Wait...thread_4: Sema Wait Successfulthread_4: Sema Postthread_3: Sema Wait...thread_3: Sema Wait Successfulthread_3: Sema Postthread_2: Sema Wait...thread_2: Sema Wait Successfulthread_2: Sema Postthread_1: Sema Wait...thread_1: Sema Wait Successfulthread_1: Sema Postthread_4: Sema Wait...thread_4: Sema Wait Successfulthread_4: Sema Postthread_3: Sema Wait...thread_3: Sema Wait Successfulthread_3: Sema Postthread_2: Sema Wait...thread_2: Sema Wait Successfulthread_2: Sema Postthread_4: Sema Wait...thread_4: Sema Wait Successfulthread_4: Sema Postthread_3: Sema Wait...thread_3: Sema Wait Successfulthread_3: Sema Postthread_4: Sema Wait...thread_4: Sema Wait Successfulthread_4: Sema Postthreads stop#
5.2、有名信號量
運行結果如下:
# utils_name_semaphore2017-8-5 1924, thread_a: start2017-8-5 19:43:24, thread_b: start2017-8-5 19:43:24, thread_c: start2017-8-5 19:43:24, thread_a: sema wait...2017-8-5 19:43:24, thread_a: sema wait success2017-8-5 19:43:24, thread_b: sema trywait...2017-8-5 19:43:24, thread_b: sema tryWait failed and sleep 1 sec2017-8-5 19:43:24, thread_c: sema timedwait 1 sec...2017-8-5 19:43:25, thread_a: sema count = 12017-8-5 19:43:25, thread_c: sema timedwait failed and sleep 1 sec2017-8-5 19:43:25, thread_a: sema post and sleep 1 sec2017-8-5 19:43:25, thread_b: sema trywait...2017-8-5 19:43:25, thread_b: sema trywait success2017-8-5 19:43:26, thread_a: sema wait...2017-8-5 19:43:26, thread_c: sema timedwait 1 sec...2017-8-5 19:43:26, thread_b: sema count = 112017-8-5 19:43:26, thread_b: sema post and sleep 1 sec2017-8-5 19:43:26, thread_a: sema wait success2017-8-5 19:43:27, thread_c: sema timedwait failed and sleep 1 sec2017-8-5 19:43:27, thread_b: sema trywait...2017-8-5 19:43:27, thread_b: sema tryWait failed and sleep 1 sec2017-8-5 19:43:27, thread_a: sema count = 122017-8-5 19:43:27, thread_a: sema post and sleep 1 sec2017-8-5 19:43:28, thread_c: sema timedwait 1 sec...2017-8-5 19:43:28, thread_c: sema timedwait success2017-8-5 19:43:28, thread_b: sema trywait...2017-8-5 19:43:28, thread_a: sema wait...2017-8-5 19:43:28, thread_b: sema tryWait failed and sleep 1 sec2017-8-5 19:43:28, thread_c: sema count = 1122017-8-5 19:43:28, thread_c: sema post2017-8-5 19:43:28, thread_c: sema timedwait 1 sec...2017-8-5 19:43:28, thread_a: sema wait success2017-8-5 19:43:29, thread_b: sema trywait...2017-8-5 19:43:29, thread_b: sema tryWait failed and sleep 1 sec2017-8-5 19:43:29, thread_c: sema timedwait failed and sleep 1 sec2017-8-5 19:43:29, thread_a: sema count = 1132017-8-5 19:43:29, thread_a: sema post and sleep 1 sec2017-8-5 19:43:30, thread_b: sema close2017-8-5 19:43:30, thread_c: sema timedwait 1 sec...2017-8-5 19:43:30, thread_c: sema timedwait success2017-8-5 19:43:30, thread_a: sema wait...2017-8-5 19:43:31, thread_c: sema count = 2132017-8-5 19:43:31, thread_c: sema post2017-8-5 19:43:31, thread_c: sema close2017-8-5 19:43:31, thread_a: sema wait success2017-8-5 19:43:32, thread_a: sema count = 2142017-8-5 19:43:32, thread_a: sema post and sleep 1 sec2017-8-5 19:43:33, thread_a: sema wait...2017-8-5 19:43:33, thread_a: sema wait success2017-8-5 19:43:34, thread_a: sema count = 2152017-8-5 19:43:34, thread_a: sema post and sleep 1 sec2017-8-5 19:43:35, thread_a: sema closethreads stop#
-
編譯
+關注
關注
0文章
663瀏覽量
33079 -
線程
+關注
關注
0文章
507瀏覽量
19766 -
OpenHarmony
+關注
關注
25文章
3753瀏覽量
16700
發布評論請先 登錄
相關推薦
基于ArkTS語言的OpenHarmony APP應用開發:HelloOpenharmony
![基于ArkTS語言的<b class='flag-5'>OpenHarmony</b> APP應用開發:Hello<b class='flag-5'>Openharmony</b>](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
基于OpenHarmony標準系統的C++公共基礎類庫案例:rwlock
![基于<b class='flag-5'>OpenHarmony</b><b class='flag-5'>標準系統</b>的<b class='flag-5'>C++</b><b class='flag-5'>公共</b>基礎<b class='flag-5'>類</b><b class='flag-5'>庫</b>案例:rwlock](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
基于OpenHarmony標準系統的C++公共基礎類庫案例:SafeQueue
![基于<b class='flag-5'>OpenHarmony</b><b class='flag-5'>標準系統</b>的<b class='flag-5'>C++</b><b class='flag-5'>公共</b>基礎<b class='flag-5'>類</b><b class='flag-5'>庫</b>案例:SafeQueue](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
基于OpenHarmony標準系統的C++公共基礎類庫案例:SafeStack
![基于<b class='flag-5'>OpenHarmony</b><b class='flag-5'>標準系統</b>的<b class='flag-5'>C++</b><b class='flag-5'>公共</b>基礎<b class='flag-5'>類</b><b class='flag-5'>庫</b>案例:SafeStack](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
基于OpenHarmony標準系統的C++公共基礎類庫案例:SafeBlockQueue
![基于<b class='flag-5'>OpenHarmony</b><b class='flag-5'>標準系統</b>的<b class='flag-5'>C++</b><b class='flag-5'>公共</b>基礎<b class='flag-5'>類</b><b class='flag-5'>庫</b>案例:SafeBlockQueue](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
評論