2020年3月31日 星期二

c++ class thread

#include <iostream>
#include <thread>
#include <unistd.h>     
using namespace std; 

class threadData{
  private:
   int value;
   thread* t;
   
  public:
   threadData(int x){
    value = x;
   }
   
   int getValue(){
    return value;
   }
   
   void threadHead(){
    while(value < 20){
     value++;
     cout  << "thread value =" << value << "\n";
     sleep(1);
    };
   }
   
   int startThread(){
    t = new thread(&threadData::threadHead, this);
   }
  
};


int main() { 
 int time = 0;
 threadData test1(3);
 cout << "value 1 = " << test1.getValue() << "\n";
 test1.startThread();
 
 while(time < 10){
  time++;
  sleep(1);
  cout << "sleep  = " << test1.getValue() << "\n";
 }


    return 0; 
}

g++ -std=c++11 -o test1 -pthread haha.cpp

沒有留言:

張貼留言