#include <cstdio>
#include <thread>
#include <chrono>
#include <mutex>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
using namespace std::chrono;
int main(int argc,char* argv[])
{
int fd,fd_dup;
int index=0;
mutex mut;
fd_dup=dup(STDOUT_FILENO);
fd=dup(STDOUT_FILENO);
thread dup_thread([&]() //must be reference
{
while(true)
{
this_thread::sleep_for(milliseconds(700)); //sleep for 700 ms
lock_guard<mutex> guard(mut);
if(index<20)
{
printf("dup_thread: index= %d\n",index); //output
++index;
}
else
break;
}
close(fd_dup);
return ;
}
);
while(true)
{
this_thread::sleep_for(seconds(1));
lock_guard<mutex> guard(mut);
if(index<20)
{
printf("main_thread: index= %d\n",index);
++index;
}
else
break;
}
dup_thread.join();
close(fd);
return 0;
}
g++ -std=c++11 -pthread -g -Wall test_dup.cpp
./a.out