diff --git a/test/src/cpp11/.vscode/settings.json b/test/src/cpp11/.vscode/settings.json index 9dc95fe..a1b54cd 100644 --- a/test/src/cpp11/.vscode/settings.json +++ b/test/src/cpp11/.vscode/settings.json @@ -50,6 +50,8 @@ "xstring": "cpp", "xtr1common": "cpp", "xutility": "cpp", - "ctime": "cpp" + "ctime": "cpp", + "threadpool.h": "c", + "*.rh": "cpp" } } \ No newline at end of file diff --git a/test/src/cpp11/cpp11_test.cpp b/test/src/cpp11/cpp11_test.cpp index 4f75b55..d2df55d 100644 --- a/test/src/cpp11/cpp11_test.cpp +++ b/test/src/cpp11/cpp11_test.cpp @@ -2,12 +2,12 @@ using namespace std; #include #include "thread_usage.h" +#include "threadpool.h" int main(){ std::cout<<"test start"< lck (gMtx); + print_even(id); + } + catch (std::logic_error& e ) { + std::cout << "[exception caught]: "; + std::cout<< e.what()< lck(cMtx); + while (!gReady) // 如果标志位不为 true, 则等待... + gCv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后, + // 线程被唤醒, 继续往下执行打印线程编号id. + std::cout << "thread " << id << '\n'; +} + +void go(){ + std::unique_lock lck(cMtx); + gReady = true; // 设置全局标志位为 true. + gCv.notify_one(); // 唤醒所有线程. +} + +int TestConditionVariable() { + std::thread threads[10]; + // spawn 10 threads: + for (int i = 0; i < 10; ++i) + threads[i] = std::thread(do_print_id, i); + std::cout << "10 threads ready to race...\n"; + go(); // go! + for (auto & th:threads) + th.join(); + return 0; +} \ No newline at end of file diff --git a/test/src/cpp11/thread_usage.h b/test/src/cpp11/thread_usage.h index df09ac2..8c26287 100644 --- a/test/src/cpp11/thread_usage.h +++ b/test/src/cpp11/thread_usage.h @@ -8,4 +8,6 @@ #include void TestPromiseFutureBefore(); -void TestThreadDetch(); \ No newline at end of file +void TestThreadDetach(); +void TestLockGuard(); +int TestConditionVariable(); \ No newline at end of file diff --git a/test/src/cpp11/threadpool.c b/test/src/cpp11/threadpool.c new file mode 100644 index 0000000..e6d861c --- /dev/null +++ b/test/src/cpp11/threadpool.c @@ -0,0 +1,18 @@ +#include "threadpool.h" + +int ThreadPool::AddTask(){ + +} + +void ThreadPool::Start(){ + +} + +void ThreadPool::Stop(){ + for (auto & th:threads) + th.join(); +} + +bool ThreadPool::Started(){ + +} \ No newline at end of file diff --git a/test/src/cpp11/threadpool.cpp b/test/src/cpp11/threadpool.cpp new file mode 100644 index 0000000..655ef9e --- /dev/null +++ b/test/src/cpp11/threadpool.cpp @@ -0,0 +1 @@ +#include "threadpool.h" \ No newline at end of file diff --git a/test/src/cpp11/threadpool.h b/test/src/cpp11/threadpool.h new file mode 100644 index 0000000..2a33139 --- /dev/null +++ b/test/src/cpp11/threadpool.h @@ -0,0 +1,19 @@ +#pragma once +#include +#include +#include +#include + +using namespace std; + +typedef class CThreadPool { +public: + CThreadPool(int num); + int AddTask(); + void Start(); + void Stop(); + bool Started(); +private: + bool mStarted; + std::vector mThreads; +}ThreadPool; \ No newline at end of file