Firstly, I'm using VS2008 (doesn't support C++11). I can't upgrade and need to use native libraries only because it needs to be compiled on another persons' compiler which I don't have control over.
I would like to run the code automatically after 5 seconds without having to poll how many seconds have elapsed.
This is my incomplete code
#include <windows.h>
#include <iostream>
void runMeAfterFiveSeconds(){
cout<<"I'm activated!"<<endl;
}
void main(){
while(1){
cout<<"hello there!"<<endl;
Sleep(2000);
}
}
Example output
hello there!
hello there! //after 2 seconds
hello there! //after 4 seconds
I'm activated! //after 5 seconds
hello there! //after 6 seconds
hello there! //after 8 seconds
hello there! //after 10 seconds
I'm activated! //after 10 seconds
...
This example shows how to do it using a very simple scheduling algorithm. No spawning of additional threads is required.
#include <stdio.h>
#include <windows.h>
int main(int argc, char ** argv)
{
DWORD now = timeGetTime();
DWORD nextPrintHelloThereTime = now;
DWORD nextPrintImActivatedTime = now+5000;
while(1)
{
now = timeGetTime();
DWORD nextEventTime = (nextPrintHelloThereTime < nextPrintImActivatedTime) ? nextPrintHelloThereTime : nextPrintImActivatedTime;
DWORD millisecondsToSleep = nextEventTime-now;
Sleep(millisecondsToSleep);
now = timeGetTime();
if (now >= nextPrintHelloThereTime)
{
printf("hello there!\n");
nextPrintHelloThereTime += 2000;
}
if (now >= nextPrintImActivatedTime)
{
printf("I'm activated!\n");
nextPrintImActivatedTime += 5000;
}
}
}
It really depends on what code you want to execute and how you want it to be executed.
The very simple way of doing so would be creating a separate thread and Sleep() in it.
So, since you cannot upgrade from Visual Studio 2008 (which, if I remember correctly, does not support C++11), you have to use either native Windows threads or some library implementation like Boost.Thread.
To look up how to use Windows threads, see MSDN documentation on _beginthreadex() function.
A short tutorial about Boost.Thread can bee seen here.
Quick examples of both, taken directly from the links I provided:
1) Windows threads:
// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>
unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );
while ( Counter < 1000000 )
Counter++;
_endthreadex( 0 );
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadID;
printf( "Creating second thread...\n" );
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
printf( "Counter should be 1000000; it is-> %d\n", Counter );
// Destroy the thread object.
CloseHandle( hThread );
}
2) Boost.Thread:
struct callable
{
void operator()();
};
boost::thread copies_are_safe()
{
callable x;
return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK
In the second example, you could as well have used a plain function pointer as boost::thread constructor argument. Moreover, you could use a pointer to function with multiple arguments - a luxury Windows API's threads do not provide.
You're probably just going to need to create a thread like so:
#include <windows.h>
#include <iostream>
#include <thread>
void runMeAfterFiveSeconds(){
while(true){
sleep(5000);
cout<<"I'm activated!"<<endl;
}
}
void main(){
std::thread th(runMeAfterFiveSeconds);
while(1){
cout<<"hello there!"<<endl;
Sleep(2000);
}
}
You're going to have to either make a thread (Coding Orange's answer, probably the better way), or just write it all out.
void runMeAfterFiveSeconds(){
cout << "I'm activated!" <<endl;
}
void main(){
while(1){
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
Sleep(3000);
runMeAfterFiveSeconds();
Sleep(1000);
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
Sleep(2000);
cout << "hello there!" << endl;
runMeAfterFiveSeconds();
}
}
Related
I want to add a delay so that one line will run and then after a short delay the second one will run. I'm fairly new to C++ so I'm not sure how I would do this whatsoever. So ideally, in the code below it would print "Loading..." and wait at least 1-2 seconds and then print "Loading..." again. Currently it prints both instantaneously instead of waiting.
cout << "Loading..." << endl;
// The delay would be between these two lines.
cout << "Loading..." << endl;
in c++ 11 you can use this thread and crono to do it:
#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);
to simulate a 'work-in-progress report', you might consider:
// start thread to do some work
m_thread = std::thread( work, std::ref(*this));
// work-in-progress report
std::cout << "\n\n ... " << std::flush;
for (int i=0; i<10; ++i) // for 10 seconds
{
std::this_thread::sleep_for(1s); //
std::cout << (9-i) << '_' << std::flush; // count-down
}
m_work = false; // command thread to end
m_thread.join(); // wait for it to end
With output:
... 9_8_7_6_5_4_3_2_1_0_
work abandoned after 10,175,240 us
Overview: The method 'work' did not 'finish', but received the command to abandon operation and exit at timeout. (a successful test)
The code uses chrono and chrono_literals.
In windons OS
#include <windows.h>
Sleep( sometime_in_millisecs ); // note uppercase S
In Unix base OS
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals
You want the sleep(unsigned int seconds) function from unistd.h. Call this function between the cout statements.
This is my code:
void* task1(void* unused)
{
try {
cout << "Run Thread" << endl;
}catch (const char* msg) {
cout << msg << endl;
}
}
int main(int argc, char *argv[])
{
try {
pthread_t thread_id;
int res = pthread_create(&thread_id, NULL, &task1, NULL);
cout << res << std::endl;
exit(EXIT_SUCCESS);
}catch (const char* msg) {
cout << msg << endl;
}
}
In Ubuntu Code RUN.
In CentOS Code NOT RUN, if my use pthread_join(thread_id, NULL); code is run but can waiting pthread complete. I try pthread_tryjoin_np but code not run.
Please help me run code in centos is no wating
If the program main() exits before the thread actually starts (and runs to the point cout << ...), the thread will be terminated and not continue to run.
I.e. you need to wait with pthread_join() before the main() exits.
The case in Ubuntu is a pure coincidence, that the thread manages to print the line before it is terminated by the C++ runtime after the main() exits.
If you do not want to wait because you want to start multiple threads, you can use thread pool (array of threads). First you start all of them, and then you pthread_join() wait for all of them to finish.
Also, if the pthread_join() blocks although the thread terminated, make sure you created the thread as joinable. That is the default, so make sure that you do not explicitly set the thread attributes to PTHREAD_CREATE_DETACHED.
To be absolutely sure, you can provide thread create attributes explicitly and ensure that the thread is created as joinable:
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread_id, &attr, &task1, NULL);
pthread_attr_destroy(&attr);
pthread_join(thread_id, NULL);
(error handling not included)
Why you do not use C ++ 11? Standard library (STL) have the opportunity to develop crossplatform applications with threads. You can test on cpp.sh
#include <iostream>
#include <thread>
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
}
int main()
{
std::thread thr(task1,1);
thr.join();
return 0;
}
OR
#include <iostream>
#include <thread>
#include <chrono>
bool bThread = false;
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
bThread = true;
}
int main()
{
std::thread thr(task1,1);
try
{
thr.detach();
while (!bThread) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
catch(...) { return 1; }
return 0;
}
I am trying to run a loop until the user chooses to break out of it. Whether the user wants to run the function all night or for just a few seconds the loop should repeat until the user decides to stop it.
In researching solutions I came across using two threads to achieve this. The first thread would run the infinite loop while the second thread waited for user input. Upon receiving that input the second thread would terminate the first and then return.
How do I use the second thread to terminate the first?
#include <iostream>
#include <iomanip>
#include <ctime>
#include <thread>
#include <cstdlib>
#include <Windows.h>
using namespace std;
void timeCount()
{
time_t rawTime;
struct tm * timeinfo;
do
{
Sleep(500);
system("cls");
time(&rawTime);
cout << "Seconds passed this epoch:" << rawTime << endl << endl;
timeinfo = localtime(&rawTime);
cout << "The local time is:" << asctime(timeinfo) << endl;
timeinfo = gmtime(&rawTime);
cout << "The UTC time is :" << asctime(timeinfo) << endl;
} while (1 != 0);
};
void getStop()
{
system("pause");
};
void timeSince()
{
thread counter(timeCount);
thread stopper(getStop);
counter.detach();
stopper.join();
counter.~thread();
};
I usually use an atomic<int> or atomic<bool> to do it.
Thread function
void run( atomic<bool> & quit ) {
while (!quit) {
// Do some work.
}
}
Mainthread:
int main() {
// Just to show you can do this with more than 1 extra thread.
unsigned int nThreads = std::thread::hardware_concurrency();
std::atomic<bool> loopFlags[nThreads];
std::thread threads[nThreads];
// Start threads
for ( int i = 0; i < nThreads; i++) {
loopFlags[i] = false;
threads[i] = std::thread(run, std::ref(loopFlags[i]));
}
usleep(10000); // Sleep for a while or do something else.
// Shutdown other threads
for ( auto & flag : loopFlags ) {
flag = true;
}
// Wait for threads to actually finish.
for ( auto& thread : threads ) {
thread.join();
}
// Resume what you were doing.
}
What is the simplest way of making a thread in c++? I want to make one that uses an already declared method to run. Something like:
void task1(){
cout << "Thread started";
}
thread t1 = thread(task1());
I guess I want to make a thread that doesn't require downloading any libraries and that my compiler will most likely be able to compile. And a big question I want answered is, what is c++11? Is it a whole different language, or a bundle of libraries?
C++11 has thread library. A very simple example is:
#include <iostream>
#include <thread>
void task1()
{
std::cout<<"Thread started\n";
}
int main()
{
std::thread t1(task1);
t.join();
}
See http://en.cppreference.com/w/cpp/thread/thread
If you can't use C++11, it depends upon what you are programming for. The following "simple as possible" threading example is written in unmanaged Win32 code, using the CreateThread function:
#include <Windows.h>
#include <tchar.h>
#include <iostream>
using namespace std;
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
WORD numSeconds = 0;
for (;;) {
Sleep(1000);
cout << numSeconds++ << " seconds elapsed in child thread!" << endl;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[]) {
HANDLE hThread;
DWORD threadID;
WORD numSeconds = 0;
cout << "Hello world" << endl;
hThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID);
Sleep(500);
for (;;) {
cout << numSeconds++ << " seconds elapsed in main thread!" << endl;
Sleep(1000);
}
return 0;
}
If you use this approach, remember that the function pointer passed to CreateThread must have the signature:
DWORD ThreadFuncion(LPVOID lpParameter);
You can find the description of that signature on MSDN.
C++ standard gets revised often every few years. Some cool things get added and old things are kept for backward compatibility. Here is some history.
Boost has a very good influence in driving the C++ standard.
I want to know how to run a thread to sleep some time every time I press a key. For example, if I press the same key twice, it should have two threads to sleep for a while.
I MUST use pthreads and C++.
Honestly I have tried many ways but I still do not know how to solve it.
Sorry if my english is not very good :)
UPDATE
This is my code:
#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
int a;
void* executer2(void*)
{
pthread_mutex_lock(&mutex);
while (a > 0) {
pthread_cond_wait(&cond, &mutex);
}
cout << "Thread: " << pthread_self() << endl;
sleep(a);
pthread_mutex_unlock(&mutex);
}
void* executer(void*)
{
int key;
while (1) {
pthread_mutex_lock(&mutex);
key = cin.get();
if (key == 'a') {
cout << "Sleep for 4 seconds" << endl;
a = 4;
} else if (key == 'b') {
cout << "Sleep for 8 seconds" << endl;
a = 8;
} else {
cout << "Sleep for 2 seconds" << endl;
a = 2;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t tr, t;
pthread_attr_t attr;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&tr, &attr, executer, NULL);
pthread_create(&t, &attr, executer2, NULL);
pthread_join(tr, NULL);
pthread_join(t, NULL);
}
since you want to create a thread each time you press a key, and that the keypress handler is in executer, you should move the code to create executer2 in executer.
executer is made to sleep 1 sec. after reading a key press, but it seems that's not what you want. Just remove that call to sleep(1) to get an immediate response
the code of executer seems to indicate that you wish to modulate the time spent sleeping by the thread depending on the input key. You can pass the sleep time as a parameter to executer2, as indicated by the void * parameter of that function. The idea is to cast the time value to a void *, pass it at thread creation time, and cast it back to int within executer2:
// executer2 thread creation
pthread_create(&t, &attr, executer2,(void *)a);
and in executer2:
void *executer2(void *arg){
int a = (int)arg;
// ...
The thread creation code should go after the switch in executer2, and you should not need the global a variable anymore.
you are currently using a mutex to lock the code of executer2. This will prevent all the sleeping threads to sleep together at the same time. You will have to remove the lock to allow them to sleep concurrently (but leave the lock around the text output).
you say that you wish a C++ solution. You could benefit from using the thread library from the stl, which wraps the OS thread primitives (pthreads in your case) with higher level constructs and are easier to manipulate, especially for parameters. It would be a good exercise to convert your programme to use this library once you have the current code working.