aboutsummaryrefslogtreecommitdiffhomepage
path: root/content/20210515-pthread_cancel-noexcept
diff options
context:
space:
mode:
authorjohannst <johannes.stoelp@gmail.com>2021-05-15 22:17:43 +0200
committerjohannst <johannes.stoelp@gmail.com>2021-05-15 22:17:43 +0200
commit1a088951089023d4ee18f01a0b83b71287c4d847 (patch)
tree20186d534b168fa3112d951104971f0cd33d4f37 /content/20210515-pthread_cancel-noexcept
parentd699ee5b1f1f435ef983a00c531bf0df2aeaa0a8 (diff)
downloadblog-1a088951089023d4ee18f01a0b83b71287c4d847.tar.gz
blog-1a088951089023d4ee18f01a0b83b71287c4d847.zip
new post: pthread_cancel in c++
Diffstat (limited to 'content/20210515-pthread_cancel-noexcept')
-rw-r--r--content/20210515-pthread_cancel-noexcept/thread.cc40
1 files changed, 40 insertions, 0 deletions
diff --git a/content/20210515-pthread_cancel-noexcept/thread.cc b/content/20210515-pthread_cancel-noexcept/thread.cc
new file mode 100644
index 0000000..73370be
--- /dev/null
+++ b/content/20210515-pthread_cancel-noexcept/thread.cc
@@ -0,0 +1,40 @@
+// file : thread.cc
+// compile: g++ thread.cc -o thread -lpthread
+
+#include <atomic>
+
+#include <pthread.h>
+#include <unistd.h>
+
+struct S {
+ ~S() {
+ const char msg[] = "cancellation-point\n";
+ // write() -> pthread cancellation point.
+ write(STDOUT_FILENO, msg, sizeof(msg));
+ }
+};
+
+std::atomic<bool> gReleaseThread{false};
+
+void* threadFn(void*) {
+ while (!gReleaseThread) {}
+
+ // Hit cancellation point in destructor which
+ // is implicitly `noexcept`.
+ S s;
+
+ return nullptr;
+}
+
+int main() {
+ pthread_t t;
+ pthread_create(&t, nullptr /* attr */, threadFn, nullptr /* arg */);
+
+ // Cancel thread and release it to hit the cancellation point.
+ pthread_cancel(t);
+ gReleaseThread = true;
+
+ pthread_join(t, nullptr /* retval */);
+
+ return 0;
+}