Synchronization in Pthread C++ - c++

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).

Related

Why is it bad to pass an ID to a thread in the following way?

I am currently trying to learn POSIX threads and made the simple code that you can see below.
I have been told that it is bad to pass an ID to a thread as you can see I did in this code snippet:
int ID0= 0;
int ID1 = 1;
pthread_create(&thread_zero, NULL, thread_function, (void*)&ID0);
pthread_create(&thread_one, NULL, thread_function, (void*)&ID1);
Why is that?
Also, would it be better to use pthread_self?
The full code:
#include <iostream>
#include <pthread.h>
#include <unistd.h>
void *thread_function(void *arg)
{
for(int i =0; i<=10;i++)
{
std::cout << "Hello # " << i<< " From thread : " <<*((int*)arg) << std::endl;
sleep(1);
}
std::cout <<"Thread "<<*((int*)arg)<< " terminates" << std::endl;
pthread_exit(NULL);
}
int main(){
pthread_t thread_zero;
pthread_t thread_one;
int ID0= 0;
int ID1 = 1;
pthread_create(&thread_zero, NULL, thread_function, (void*)&ID0);
pthread_create(&thread_one, NULL, thread_function, (void*)&ID1);
std::cout << "main: Creating threads" << std::endl;
std::cout << "main: Wating for threads to finish" << std::endl;
pthread_join(thread_zero, NULL);
pthread_join(thread_one, NULL);
std::cout<<"Main: Exiting"<<std::endl;
return 0;
}
Why is that?
There is nothing wrong with your code, so long as you ensure that the ID0 and ID1 do not go out of scope before you join your threads, and that either thread does not modify ID0 and ID1 without proper synchronization.
In general, when passing an entity into thread that is not larger than (void*), it is safer to pass it by value, like so:
pthread_create(&tid, NULL, fn, (void*)ID0);
When done that way, ID0 can go out of scope with no danger that the new thread will access dangling stack, and no danger of a data race (which is undefined behavior).

cancelling std::thread using native_handle() + pthread_cancel()

I am converting a previous thread wrapper around pthreads to std::thread.
However c++11 does not have any way to cancel the thread. I REQUIRE, nonetheless, to cancel threads since they may be performing a very lengthy task inside an external library.
I was considering using the native_handle that gives me pthread_id in my platform. I'm using gcc 4.7 in Linux (Ubuntu 12.10). The idea would be:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main(int argc, char **argv) {
cout << "Hello, world!" << endl;
auto lambda = []() {
cout << "ID: "<<pthread_self() <<endl;
while (true) {
cout << "Hello" << endl;
this_thread::sleep_for(chrono::seconds(2));
}
};
pthread_t id;
{
std::thread th(lambda);
this_thread::sleep_for(chrono::seconds(1));
id = th.native_handle();
cout << id << endl;
th.detach();
}
cout << "cancelling ID: "<< id << endl;
pthread_cancel(id);
cout << "cancelled: "<< id << endl;
return 0;
}
The thread is canceled by an exception thrown by pthreads.
My question is:
Will there be any problem with this approach (besides not being portable)?
No, I don't think that you will not have additional problems than:
not being portable
having to program _very_very_ carefully that all objects of the cancelled thread are destroyed...
For example, the Standard says that when a thread ends variables will be destroyed. If you cancel a thread this will be much harder for the compiler, if not impossible.
I would, therefore recommend not to cancel a thread if you can somehow avoid it. Write a standard polling-loop, use a condition variable, listen on a signal to interrupt reads and so on -- and end the thread regularly.

Create a child thread that is independent of parent in C++

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).

multithreaded programming

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;
}

How can I execute two threads asynchronously using boost?

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;
}