detached.c

来自「C++ SOCKET 类」· C语言 代码 · 共 53 行

C
53
字号
#include <thread.h>#include <iostream>int exitCond=0;using namespace cpp_threads;class simple : public Pthread {protected:  Semaphore m_sem;public:  simple() { };  ~simple() { }  int thread(void *)  {    std::cout << "thread started." << std::endl;    while (!exitCond) {      m_sem.wait();      std::cout << "now doing some major tasks" << std::endl;      sleep(5);    }    std::cout << "phew... ending" << std::endl;    return 0;  }  Semaphore& sem() { return m_sem; };};intmain(){  simple *th = new simple();  std::cout << "Threads are like variables in a main program" << std::endl;  std::cout << "so when the main program ends, so do the threads" << std::endl;  std::cout << "as like any variable, it is cleaned up on exit." << std::endl;  std::cout << "To make a thread independant of the main program," <<std::endl;  std::cout << "set the pthread::set_detached to true." << std::endl;  th->run(); // tell the thread to run ahead  sleep(1);  // Make the thread an independant process.  th->set(Pthread::set_detached_e,true);  th->sem().post();  // Thread to do some tasks.  sleep(5);  th->sem().post();  exitCond = 1;  exit(0);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?