C++ how to sleep? - c++

I am a novice in C++ and I am struggling to make my program to wait a few minutes before executing a function.
I know there are lots of topics about it but I have a problem with my compiler. I can't seem to use the boost library nor the thread library. And since I can't use the thread library, I can't use the chrono library either.
I am using GNU GCC Compiler. I have MinGW installed. Is it outdated or something? What is the best compiler to code in C++?
My OS is Windows.

You could use this
#include <unistd.h>
...
usleep(1000); // Time in microseconds
or
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main(){
int sleepTime = 1000;
Sleep(sleepTime);
return 0;
}

<thread> is only available starting with C++11.
It's likely you don't have the proper flags to tell GCC you want to enable C++11 support, which is disabled by default.
The command line parameter is -std=c++11.
Then, you can use std::this_thread::sleep_for() for cause your program to fall asleep. Note that if you only have one thread in your program, it will probably stop responding to user actions during that time.

Related

Calling C++ program from a function?

So I'm pretty new to C++ and programming in general, and I'm trying to figure out how I can use code from this github program inside my own program. How do I write a function that calls the program and returns the results?
Here is the reference to std::system. With this you can run any command on a POSIX system.
#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
std::system("ls -l >test.txt"); // execute the UNIX command "ls -l >test.txt"
std::cout << std::ifstream("test.txt").rdbuf();
}
If you need a other platform (e.g. Windows) take a look at boost process.
This is done by asking the system to create a new process, so your solution will depend on the system you are on.
You can use directly the system interfaces to create the process, or use a cross-platform third party wrapper such as Qt or boost.

Can't resolve namespace member 'thread'

I wanted to practice with standard C++ threads instead of UNIX ones, but soon encountered a problem, whenever I write std::thread CLion underlines it with red and says Can't resolve namespace member 'thread'. I checked my CMake file it's set for C++11. I reinstalled the latest version of MinGW (6.3.0) and ticked a box with G++ compiler. I have been told by my friend that he uses Cygwin and everything works. But is it still possible to make it work with MinGW?
#include <iostream>
#include <thread>
#define BUFFER_SIZE 3
#define PROD_NUM 3
#define CONS_NUM 2
void produce(){
//production
}
void consume(){
//consumption
}
int main() {
std::cout << "Hello, World!" << std::endl;
int i,j;
std::thread producer(produce);
std::thread consumer (consume);
return 0;
}
The code itself has literally nothing
EDIT
in thread library there is
#pragma GCC system_header
#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else
#include <chrono>
#include <functional>
#include <memory>
#include <cerrno>
#include <bits/functexcept.h>
#include <bits/functional_hash.h>
#include <bits/gthr.h>
#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/**
* #defgroup threads Threads
* #ingroup concurrency
*
* Classes for thread support.
* #{
*/
/// thread
class thread
{
public:
// Abstract base class for types that wrap arbitrary functors to be
// invoked in the new thread of execution.
struct _State
{
virtual ~_State();
virtual void _M_run() = 0;
};
can you make sure if the library is available in the CLion toolchain? For example Cygwin does have the include.
CLion shows things red when it can't link codes with the library.
It is possibly a host environment variable error. Make sure your CMakeLists.txt is working and your environment variables, standard library linkage is correct as well as your compiler setup.
Compiler version and and standard libraries compatible. (e.g. you are using a cross-compiler (RasPi, Android) but environment vars shows host library etc. will make it fail)
Check this relevant post, it may help.
C++11 std::threads vs posix threads
Ok, so I finally solved the problem. I installed Cygwin and in CLion Settings I manually linked C/C++ compilers (for some reason CLion was unable to auto-detect them). Cleared all and re-indexed the project. Now it shows no errors and code compiles.
Regarding MinGW, I read on cplusplus.com some posts regarding the issue but they were about previous versions of MinGW and it was said that they finally fixed it, however I tell: No, they didn't. Here there is a nice repository and its README file suggests that thread of win32 rely on gthreads, however i found gthread file in my libraries everything seemed ok... so still need to investigate the issue. Write your ideas and experience here if you know more.
As for now solution is Cygwin, use it instead of MinGW.
P.S. Thanks #KillzoneKid for links

How to print a word every second?

How can I print a word once a second while using fopen("filename.txt","r")?
I searched earlier and found something that used the unistd.h header file, but in my Turbo C++ no such header file exists.
C++11
If your compiler supports C++11, std::thread::sleep_for is the best, cross-platform solution:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::seconds(1));
// or
using namespace std::chrono_literals;
std::this_thread::sleep_for(1s);
If you are forced to use compiler that doesn't support C++, you have to use platform-specific functions:
POSIX
sleep is part of POSIX.1-2001, so it should run on any compliant operating system, including UNIXes, Linux and Mac OS X:
#include <unistd.h>
sleep(1);
Windows
Sleep is part of WinAPI:
#include <windows.h>
Sleep(1000); // Note capital "S" and that you specify time in milliseconds

How do I setup my g++ compiler for C++11? [duplicate]

This question already has answers here:
Closed 10 years ago.
I tried a basic program:
// ThreadExample.cpp
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
thread t1(task1, "Hello");
t1.join();
}
One I actually found on stackoverflow, but I tried compiling it using:
g++ -std=c++0x -pthread ThreadExample.cpp -o ThreadExample -lm
However, I keep getting an error that thread is undeclared. I have version 4.7.1 of the MinGW GNU for Windows. Is there something I can change so I can use C++11?
Noone has contributed an implementation of <thread>, <mutex> etc for Mingw yet, except when using Mingw with (optional) Pthreads support via a third-party pthreads implementation.
I started a thread at http://gcc.gnu.org/ml/libstdc++/2012-05/msg00020.html with some suggestions for implementing the missing features in terms of Windows native threads, but as I don't have a Windows machine and noone else has volunteered to do anything, nothing happened. I have almost zero interest in implementing it myself, because I never develop for Windows so it would be of no use to me whatsoever, and I would rather spend my limited free time implementing things I will actually use. If anyone wants to work on it I'd happily advise them and review their code and help shepherd it into GCC.

C++ sleep pthread conflict

I am writing a code about the deadlocks and their detection, i use eclipse Juno C/C++ on Ubuntu 12.10, 64 bit.
The problem is when i use
sleep(1)
, i get this
sleep was not declared in this scope
when i build the project, i tried to include
include < unistd.h>
, but then all the pthread functions like
pthread_join
gives me errors like
undefined reference to pthread_join
, without #include < unistd.h> such error doesn't show up.
sample code:
#include <unistd.h>
#include <iostream>
#include <semaphore.h>
#include <queue>
#include <stdlib.h>
using namespace std;
pthread_mutex_t mutex;
sem_t sem; //used for writing in the console
.......
void cross(Batman b) {
// code to check traffic from the right, use counters, condition
sem_wait(&sem);
cout << "BAT " << b.num << " from " << b.direction << " crossing" << endl;
sem_post(&sem);
sleep(1);
}
........
p.s. i followed these instructions to get pthreads working in other project and i did the same for this project
http://blog.asteriosk.gr/2009/02/15/adding-pthread-to-eclipse-for-using-posix-threads/
p.s. i am working on this project with a friend and i used the same code he uses and still get those errors, while he doesn't
when you #include < unistd.h>, you fixed sleep function look up issue, now you have pthread library issue.
Next you need to #include <pthread.h> and link your application with pthread library
It sounds like you have two different errors,
first sleep() is undefined because you forgot to include unistd.h. I'd also include pthread.h but it sounds like it might get pulled in by one of the headers you include.
Secondly it sounds like you have a linker error add, you can either compile with -pthread or add -lpthread to the linker. The reason it doesn't show up is because linking can only be done once the files have been compiled and the first error is blocking this. I'd bet that ld doesn't like -pthread for some reason (have you installed libpthread-dev?). You can try changing -pthread to -lpthread.