I wrote the following code:
#include<iostream>
#include<pthread.h>
using namespace std;
void* func(void *i)
{
cout<<"in func "<<endl;
}
int main()
{
pthread_t threads[5];
for(int i=0;i<5;i++)
{
pthread_create(&threads[i], NULL, func, (void*)i);
cout<<"next for loop"<<endl;
}
pthread_exit(NULL);
return 0;
}
The output was:
From the output it seems that the endl line changing property after first display of 'next for loop' gets delayed and endl of 'next for loop' and 'in func' are executed one after the other. This happened everytime i ran the program. Can you tell me the reason for this delay?
I think that
cout <<"next for loop" << endl;
is a compact way of writing
cout << "next for loop";
cout << endl;
Since you are working in a multi-threaded environment, the order of execution is unpredictable. That's what happened in your particular case:
cout << "next for loop";
cout << "in func ";
cout << endl;
cout << endl;
...
Streams have locks to protect them, so they single-thread. You'll need some sort of buffer of your own to collect results while running threads.
There is not much to say about the behavior of multi-threaded code where there is no explicit control of the execution flow with locks and semaphores.
For example, in the code you have posted the following can happen:
just after pthread_create() the next for loop sentence gets printed
the newly created thread starts and prints its sentence entirely (in func and endl)
The main thread is run again and it prints the remaining endl
It may also happen that the two endl overleaps in a different way (first the one of the main thread, then the one of the newly created thread).
Note: using std::endl and \n or \r\n is not the same thing.
std::endl also includes an output buffer flushing operation.
As pointed to by some answers above cout << something << endl are two separate pieces of instructions and in a multi-threaded environment cout << endl can very well we pre-empted by another thread just after it has done cout << something. Try this C style newline character(escape sequence) :
#include<iostream>
#include<pthread.h>
using namespace std;
void* func(void *i)
{
cout<<"in func \n";
//cout << "\n";
//cout<<endl;
}
int main()
{
pthread_t threads[5];
for(int i=0;i<5;i++)
{
pthread_create(&threads[i], NULL, func, (void*)i);
cout<<"next for loop\n";
//cout << "\n";
//cout<<endl;
}
pthread_exit(NULL);
return 0;
}
Related
I am new to multi thread programming, so this question might seem a little silly, but I really need to work this out so I can apply it to my project (which is way more complicated).
Follow is my code, I am trying to have 2 threads (parent and child) to update the same shared timer as they execute and stop when the timer reaches a specific limit.
But when I compile and execute this follow piece of code, there are 2 different outcomes: 1. child prints "done by child at 200000" but the program does not exit; 2. after child prints "done by child at 200000" and exits, parent keeps executing, prints a couple of dozen lines of "parent doing work" and "parent at 190000", then prints "done by parent at 200000" and the program exits properly.
The behavior I want is for whichever thread that updates the timer, hits the limit and exits, the other thread should stop executing and exit as well. I think I might be missing something trivial here, but I've tried changing the code in many ways and nothing I tried seem to work. Any help will be much appreciated :)
#include <iostream>
#include <unistd.h>
#include <mutex>
#include <time.h>
using namespace std;
mutex mtx;
int main () {
int rc;
volatile int done = 0;
clock_t start = clock();
volatile clock_t now;
rc = fork();
if (rc == 0) { //child
while (true) {
cout << "child doing work" << endl;
mtx.lock();
now = clock() - start;
if (done) {
mtx.unlock();
break;
}
if (now >= 200000 && !done) {
done = 1;
cout << "done by child at " << now << endl;
mtx.unlock();
break;
}
cout << "child at " << now << endl;
mtx.unlock();
}
_exit(0);
}
else { // parent
while (true) {
cout << "parent doing work" << endl;
mtx.lock();
now = clock() - start;
if (done) {
mtx.unlock();
break;
}
if (now >= 200000 && !done) {
done = 1;
cout << "done by parent at " << now << endl;
mtx.unlock();
break;
}
cout << "parent at " << now << endl;
mtx.unlock();
}
}
return 0;
}
Multi-processes
Your code is multi-processes and not multi-threading: fork() will create a new separate process by duplicating the calling process.
The consequence: At the moment of the duplication, all the variables contain the same value in both processes. But each process has its own copy, so a variable modified in the parent will not be updated in the child's address space an vice-versa.
If you want to share variables between processes, you should have a look at this SO question
Multithread
For real multithreading, you should use std::thread. And forget about volatile, because it's not thread safe. Use <atomic> instead, as explained in this awesome video.
Here a first try:
#include <iostream>
#include <mutex>
#include <thread>
#include <atomic>
#include <time.h>
using namespace std;
void child (atomic<int>& done, atomic<clock_t>& now, clock_t start)
{
while (!done) {
cout << "child doing work" << endl;
now = clock() - start;
if (now >= 2000 && !done) {
done = 1;
cout << "done by child at " << now << endl;
}
cout << "child at " << now << endl;
this_thread::yield();
}
}
void parent (atomic<int>& done, atomic<clock_t>& now, clock_t start)
{
while (!done) {
cout << "parent doing work" << endl;
now = clock() - start;
if (now >= 2000 && !done) {
done = 1;
cout << "done by parent at " << now << endl;
}
cout << "parent at " << now << endl;
this_thread::yield();
}
}
int main () {
atomic<int> done{0};
clock_t start = clock();
atomic<clock_t> now;
thread t(child, std::ref(done), std::ref(now), start); // attention, without ref, you get clones
parent (done, now, start);
t.join();
return 0;
}
Note that you don't need to protect atomic accesses with a mutex, and that if you want to do, lock_guard would be recommended alternative.
This example is of course rather weak, because if you test an atomic variable if the if-condition, it's value might already have changed when entering the if-block. This doesn't cause a problem in your logic where "done" means "done". But if you'd need a more cauthious approach,
compare_exchange_weak() or compare_exchange_strong() could help further.
I have two threads in C++. One thread called alarm thread runs the function raiseAlarm() and the other thread called print thread runs the function called printMetrics. At a fixed interval, raiseAlarm sets an atomic variable to true. When the variable is true, printMetrics thread, which is spinning on the value of this atomic variable, prints some data. When I run this application, nothing happens. But if I put a cout anywhere in raiseAlarm, everything works fine. Why?
void Client::raiseAlarm()
{
bool no = false;
while(!stop.load(std::memory_order_acquire))
{
//cout << "about to sleep\n";
this_thread::sleep_for(std::chrono::seconds(captureInterval));
while(!alarm.compare_exchange_weak(no, true, std::memory_order_acq_rel))
{
no = false;
}
}
}
void Client::printMetrics()
{
bool yes = true;
while(!stop.load(std::memory_order_acquire))
{
while(!alarm.compare_exchange_weak(yes, false, std::memory_order_acq_rel) )
{
yes = true;
}
cout << "Msgs Rcvd: " << metrics.rcv_total.load(std::memory_order_acquire);
cout << "Msgs Sent: " << metrics.snd_total.load(std::memory_order_acquire);
cout << "Min latency: " << metrics.min_latency.load(std::memory_order_acquire);
cout << "Max latency: " << metrics.max_latency.load(std::memory_order_acquire);
metrics.reset();
}
}
Just a suggestion because I'm not so savvy with concurrency in C++, but make sure you don't forget to flush your output stream. Either stick a cout << flush; after all of your cout lines or add an << endl to each one (which will automatically flush your stream).
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).
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;
}
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).