This is a simple project on C++(ubuntu16.04), try to create a thread and define a condition_variable to notify thread to do something. I compile this project by cmake. So 2 files is needed: main.cpp & CMakeLists.txt
//-------------- STEP 1: create main.cpp -----------------
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <unistd.h>
using namespace std;
int number = 0;
mutex mtx;
condition_variable cond;
void test_thread();
int main(int argc, char *argv[]){
thread new_thread(test_thread);
sleep(3);
while(1){
unique_lock<mutex> locker(mtx);
number++;
cout << "set num: " << number << endl;
cond.notify_all();
locker.unlock();
sleep(3);
}
new_thread.join();
return 0;
}
void test_thread(){
cout << "I'm get in this new thread" << endl;
while(true){
unique_lock<mutex> locker(mtx);
cond.wait(locker);
cout << "--- get num: " << number << endl;
locker.unlock();
}
}
//-------------- STEP 2: create CMakeLists.txt -----------------
cmake_minimum_required(VERSION 3.15.0)
project(test_hello)
set(CMAKE_CXX_FLAGS "-std=c++11 -g -O0")
find_package(Threads)
message(STATUS "This is BINARY dir" ${HELLO_BINARY_DIR})
message(STATUS "This is SOURCE dir" ${HELLO_SOURCE_DIR})
add_executable(hello main.cpp)
target_link_libraries(hello ${CMAKE_THREAD_LIBS_INIT})
//-------------- STEP 3: compile and test this project -----------------
$ mkdir build
$ cd build
$ cmake ..
$ make
$ ./hello
finally, you should find some printing lines looks like:
I'm get in this new thread
set num: 1
--- get num: 1
set num: 2
--- get num: 2
set num: 3
--- get num: 3
set num: 4
--- get num: 4
set num: 5
--- get num: 5
set num: 6
......