I am working in a C++ DLL module where I need to perform a task for every X min independently. I tried to create a thread for the task but my main program which creates threads will also keep waiting for the child thread(s) to complete.
Could someone please help me how to create a separate process (Please provide sample code if possible) independent of main program and do the Task?
The process should take a function and run the code present in function for every X min.
EDIT:
void test(void *param)
{
cout << "In thread function" << endl;
Sleep(1000); // sleep for 1 second
cout << "Thread function ends" << endl;
_endthread();
}
int main()
{
HANDLE hThread;
cout << "Starting thread" << endl;
cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
WaitForSingleObject( hThread, INFINITE );
cout << "Main ends" << endl;
return 0;
}
WaitForSingleObject() will block main until the thread completes. If you want to run some stuff periodically from the thread function test() you'll need to put a loop there. Best with some condition to trigger ending the thread function from main() when exiting. You shouldn't call WaitForSingleObject() before you want to exit the main() method. Thus you'll have the test() method running asynchonously.
bool endThread = false;
void test(void *param)
{
cout << "In thread function" << endl;
while(!endThread)
{
Sleep(1000); // sleep for 1 second
}
cout << "Thread function ends" << endl;
_endthread();
}
int main()
{
HANDLE hThread;
cout << "Starting thread" << endl;
cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
// Do any other stuff without waiting for the thread to end
// ...
endThread = true;
WaitForSingleObject( hThread, INFINITE );
cout << "Main ends" << endl;
return 0;
}
Note that you might need to synchronize access to the endThread variable properly using a mutex or similar, the sample should just show the principle.
UPDATE:
In case you want to exit main() before the thread ends, you cannot use threads at all.
You'll need to create an independent child process as I had mentioned in my 1st comment. Lookup for the fork() and exec() functions to do this (there might be specific WinAPI methods for these also, I don't know about).
Related
I am currently making intern and I am asked to write a multi client server-client application with using C++. Hence, I'm trying to learn threading. Have one question:
I want to print "you are in thread A", then "you are in thread B", "now you are again in thread A". However it only prints first two sentences and ignores endl command. Can't exactly understand how it works. How to fix that and could you briefly explain working mechanism?
Why main thread exits before all function calls completed?
void * function1(void * arg);
void * function2(void * arg);
pthread_t thr_A, thr_B;
int main( void )
{
pthread_create(&thr_A, NULL, function1, (void*)thr_B);
pthread_create(&thr_B, NULL, function2,NULL);
return 0;
}
void * function1(void * arg)
{
cout << "You are in thread A" << endl;
pthread_join(thr_B, NULL);
cout << "now you are again in thread A" << endl;
pthread_exit((void*)thr_A);
}
void * function2(void * arg)
{
cout << " you are in thread B " << endl ;
pthread_exit((void*)thr_B);
}
In you main function you create one race condition. The threads may be started in any order, unless you specifically synchronize your code so that you enforce one or the other to start.
Therefore it is also impossible to tell which will finish first. Then you also have your main thread, it might even finish before the threads you create finish. When using pthreads you must call pthread_join in order to wait for a thread to finish. You can do that like this:
int main( void )
{
// you pass thread thr_B to function one but
// function2 might even start before function1
// so this needs more syncronisation
pthread_create(&thr_A, NULL, function1, (void*)thr_B);
pthread_create(&thr_B, NULL, function2,NULL);
//this is mandatory to wait for your functions
pthread_join( thr_A, NULL);
pthread_join( thr_B, NULL);
return 0;
}
in order to wait in function1 you need more sophisticated synchronization method for example see for example pthread_cond_wait pthread_cond_signal as explained in: https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal
You also should remove the pthread_join from function one because according man pthread join: "If multiple threads simultaneously try to join with the same thread,
the results are undefined."
Edit on comment of David hammen:
void * function1(void * arg)
{
cout << "You are in thread A" << endl;
//Remove the next line and replace by a pthread_cond_wait.
pthread_join(thr_B, NULL);
cout << "now you are again in thread A" << endl;
pthread_exit((void*)thr_A);
}
I have the book "beyond the C++ standard library" and there are no examples of multithreading using boost. Would somebody be kind enough to show me a simple example where two threads are executed using boost- lets say asynchronously?
This is my minimal Boost threading example.
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction()
{
int counter = 0;
for(;;)
{
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main()
{
// Start thread
boost::thread t(&ThreadFunction);
// Wait for Enter
char ch;
cin.get(ch);
// Ask thread to stop
t.interrupt();
// Join - wait when thread actually exits
t.join();
cout << "main: thread ended" << endl;
return 0;
}
Is it possible to create a boost::thread and run it in the background (as a daemon)?
I am trying to the following but my thread dies when main exits.
/*
* Create a simple function which writes to the console as a background thread.
*/
void countDown(int counter) {
do {
cout << "[" << counter << "]" << endl;
boost::this_thread::sleep(seconds(1));
}while(counter-- > 0);
}
int main() {
boost::thread t(&countDown, 10);
if(t.joinable()) {
cout << "Detaching thread" << endl;
t.detach(); //detach it so it runs even after main exits.
}
cout << "Main thread sleeping for a while" << endl;
boost::this_thread::sleep(seconds(2));
cout << "Exiting main" << endl;
return 0;
}
[rajat#localhost threads]$ ./a.out
Detaching thread
Main thread sleeping for a while
[10]
[9]
Exiting main
[rajat#localhost threads]$
When your main() exits all other threads of the process are terminated (assuming Linux, can't say for Windows).
Why not just join() that background thread at the end of the main()? Or even better - use the main thread as the "daemon" thread?
I've read about synchronized thread in Posix threads tutorial. They say that function pthread_join is used for waiting thread until it stops. But why doesn't this idea work in that case?
Here is my code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int a[5];
void* thread(void *params)
{
cout << "Hello, thread!" << endl;
cout << "How are you, thread? " << endl;
cout << "I'm glad to see you, thread! " << endl;
}
void* thread2(void *params)
{
cout << "Hello, second thread!" << endl;
cout << "How are you, second thread? " << endl;
cout << "I'm glad to see you, second thread! " << endl;
// for (;;);
}
int main()
{
pthread_t pt1, pt2;
int iret = pthread_create(&pt1, NULL, thread, NULL);
int iret2 = pthread_create(&pt2, NULL, thread2, NULL);
cout << "Hello, world!" << endl;
pthread_join(pt1, NULL);
cout << "Hello, middle!" << endl;
pthread_join(pt2, NULL);
cout << "The END" << endl;
return 0;
}
Threads are executed asynchronously, as someone already mentioned in answer to question you linked. Thread execution starts right after you create() it. So, at this point:
int iret = pthread_create(&pt1, NULL, thread, NULL);
thread() is already executing in another thread, possibly on another core (but it doesn't really matter). If you add a for (;;); in your main() right after that, you will still see thread message being printed to console.
You also misunderstood what join() does. It waits for thread termination; as your threads don't do any real work, they will (most probably) reach their ends and terminate way before you call join() on them. Once again: join() doesn't start execution of thread in given place, but waits for it to terminate (or just returns, if it's already terminated).
I have made a Queue-class containing storage vectors and mutexes.
To initialise the queue, a thread needs to be started. To make sure the thread is started correctly, the constructor waits for a signal. The thread function is a friend of the Queue-class. However, the signal is not registered when sent by the thread function. Why?
Queue::Queue()
{
(...)
pthread_mutex_init( &mutex_cond_init, NULL);
Q_ready = false;
(...)
pthread_create(&thread_ID, NULL, Queue_function, this);
pthread_mutex_lock(&mutex_cond_init);
while(!Q_ready)
{
cout << "waiting" << endl;
pthread_cond_wait(&cond_init,&mutex_cond_init);
cout << "got signal" << endl;
}
pthread_mutex_unlock(&mutex_cond_init);
cout << "Queue open." <<endl;
}
void * Queue_function (void*arg)
{
(...)
Queue * S = (Queue*) arg;
pthread_mutex_lock(&(*S).mutex_cond_init);
(*S).Q_ready = true;
pthread_cond_signal(&(*S).cond_init);
pthread_mutex_unlock(&(*S).mutex_cond_init);
(...)
}
any help would be appreciated
Have you initialised cond_init? Your code only shows initialisation of mutex_cond_init.