Use of threads in C++ - c++

Can you tell me how can I use threads in C++ programs, and how can I compile it as it will be multithreaded? Can you tell me some good site where I can start from root?
Thanks

I haven't used it myself, but I'm told that the Boost thread libraries make it incredibly easy.
http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

For Unix/Linux/BSD, there's pthread library: tutorial.
I guess there are equivalent in Win32 API.
Process and Threads
Synchronization

I use tbb_thread class from intel threading building blocks library.

There are many threads libraries wich are compatible with c++. So at first you must select one. I prefer OpenMP or POSIX threads (also known as pthreads). How to compile it depends on library you have choose.

I use a library my university prof wrote. It is very simple to implement and works really well (used it for quite some time now). I will ask his permission to share it with you.
Sorry for the wait ahead, but gotta check :)
++++++EDIT+++++++
Ok, so I talked to my prof and he doesn't mind if I share it here. Below are the .h and .cpp files for the 'RT Library' written by Paul Davies
http://www.filefactory.com/file/7efbeb/n/rt_h
http://www.filefactory.com/file/40d9a6/n/rt_cpp
Some points to be made about threads and the use of this library:
0) This tutorial will explain thread creation and use on a windows platform.
1) Threads in c++ are usually coded as part of the same source (unlike processes where each process has its own source file and function main() )
2) When a process is up and running, it can create other threads by making appropriate Kernel calls.
3) Multiple threads run faster than multiple processes since they are a part of the same process which results in less of an overhead for the OS, and reduced memory requirements.
4) What you will be using in your case is the CThread class in the rt library.
5) (Make sure rt.h and rt.cpp are a part of your 'solution' and make sure to include rt.h in your main.cpp)
6) Below is a part of code from your future main thread (in main.cpp, of course) where you will create the thread using the CThread class.
void main()
{
CThread t1(ChildThread1, ACTIVE, NULL) ;
. . .
t1.WaitForThread() ; // if thread already dead, then proceed, otherwise wait
}
The arguments of t1 in order are: Name of the function acting as our thread, the thread status (it can be either ACTIVE or SUSPENDED - depending on what you want), and last, a pointer to an optional data you may want to pass to the thread at creation. After you execute some code, you'll want to call the WaitForThread() function.
7) Below is a part of code from your future main thread (in main.cpp, of course) where you will describe what the child thread does.
UINT _ _stdcall ChildThread1(void *args)
{
. . .
}
The odd looking thing there is Microsoft's thread signature. I'm sure with a bit of research you can figure out how to do this in other OSs. The argument is the optional data that could be passed to the child at creation.
8) You can find the detailed descriptions of the member functions in the rt.cpp file. Here are the summaries:
CThread() - The constructor responsible for creating the thread
Suspend() - Suspends a child thread effectively pausing it.
Resume() - Wakes up a suspended child thread
SetPriority(int value) - Changes the priority of a child thread to the value
specified
Post(int message) - Posts a message to a child thread
TerminateThread() - Terminates or Kills a child thread
WaitForThread() - Pauses the parent thread until a child thread terminates.
If the child thread has already terminated, parent will not pause
9) Below is an example of a sample complete program. A clever thing you can do is create multiple instantiations of a single thread.
#include “..\wherever\it\is\rt.h” //notice the windows notation
int ThreadNum[8] = {0,1,2,3,4,5,6,7} ; // an array of thread numbers
UINT _ _stdcall ChildThread (void *args) // A thread function
{
MyThreadNumber = *(int *)(args);
for ( int i = 0; i < 100; i ++)
printf( "I am the Child thread: My thread number is [%d] \n", MyThreadNumber) ;
return 0 ;
}
int main()
{
CThread *Threads[8] ;
// Create 8 instances of the above thread code and let each thread know which number it is.
for ( int i = 0; i < 8; i ++) {
printf ("Parent Thread: Creating Child Thread %d in Active State\n", i) ;
Threads[i] = new CThread (ChildThread, ACTIVE, &ThreadNum[i]) ;
}
// wait for threads to terminate, then delete thread objects we created above
for( i = 0; i < 8; i ++) {
Threads[i]->WaitForThread() ;
delete Threads[i] ; // delete the object created by ‘new’
}
return 0 ;
}
10) That's it! The rt library includes a bunch of classes that enables you to work with processes and threads and other concurrent programming techniques. Discover the rest ;)

You may want to read my earlier posting on SO.
(In hindsight, that posting is a little one-sided towards pthreads. But I'm a Unix/Linux kind of guy. And that approach seemed best with respect to the original topic.)

Usage of threads in C/C++:
#include <iostream>
using namespace std;
extern "C"
{
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
}
int main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
iret1 = pthread_create( &thread1, NULL, print_message_function (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
//printf("Thread 1 returns: %d\n",iret1);
//printf("Thread 2 returns: %d\n",iret2);
cout<<"Thread 1 returns: %d\n"<<iret1;
cout<<"Thread 2 returns: %d\n"<<iret2;
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
//printf("%s \n", message);
cout<<"%s"<<message;
}

Related

Cancelling boost thread from another

Is there a way to cancel a boost::thread from another as in the following?:
boost::thread* thread1(0);
boost::thread* thread2(0);
thread2 = new boost::thread([&](){
//some expensive computation that can't be modified
if(thread1)
thread1->interrupt();
});
thread1 = new boost::thread([&]() {
//some other expensive computation that can't be modified
if(thread2)
thread2->interrupt();
});
thread1->join();
thread2->join();
delete thread1;
delete thread2;
Right now both expensive computations finish without being interrupted. I had figured the joins would be treated as an interruption point, and the main thread would continue after one of the two expensive computations completed.
In general, there is no portable way for one thread to terminate another, without cooperation from the thread being terminated. This question comes up once in a while, it seems (see here and here - although your question is not an exact duplicate).
Barring cooperation from the thread being interrupted (which would have to perform seppuku on notification), if you would like the main thread to continue after the first of the threads has terminated, you could make a condition that each of the child threads fires when it ends.
At this point, you could either let the other thread continue running (possibly detaching it), or just terminate everything.
A non-portable solution for POSIX-compliant systems (e.g. Linux) would be to use pthread_cancel() and then pthread_join() on the Boost thread's native_handle() member, which is of type pthread_t (again, only on POSIX-compliant systems. I can't speak for other systems, like Windows).
Also, you must use a boost::scoped_thread instead of just a boost::thread so that you can "override" (not in the OO-sense) the join/detach behavior that Boost will do when the thread is destroyed. This is necessary because when you call pthread_cancel then pthread_join on a boost::thread, the boost::thread object is still 'joinable' (i.e. boost::thread::joinable() returns true), and so the destructor will exhibit undefined behavior, per the documentation.
With all that being said, if a platform-dependent solution for cancelling threads like this is necessary in your application, I'm not sure there's much to be gained from using boost::threads over plain-old pthreads; still, I suppose there may be a use case for this.
Here's a code sample:
// compilation: g++ -pthread -I/path/to/boost/include -L/path/to/boost/libs -lboost_thread main.cpp
#include <cstdio>
#include <pthread.h>
#include <boost/thread/scoped_thread.hpp>
typedef struct pthreadCancelAndJoin
{
void operator()(boost::thread& t)
{
pthread_t pthreadId = t.native_handle();
int status = pthread_cancel(pthreadId);
printf("Cancelled thread %lu: got return value %d\n", pthreadId, status);
void* threadExitStatus;
status = pthread_join(pthreadId, &threadExitStatus);
printf("Joined thread %lu: got return value %d, thread exit status %ld\n",
pthreadId, status, (long)threadExitStatus);
}
} pthreadCancelAndJoin;
void foo()
{
printf("entering foo\n");
for(int i = 0; i < 2147483647; i++) printf("f"); // here's your 'expensive computation'
for(int i = 0; i < 2147483647; i++) printf("a");
printf("foo: done working\n"); // this won't execute
}
int main(int argc, char **argv)
{
boost::scoped_thread<pthreadCancelAndJoin> t1(foo);
pthread_t t1_pthread = t1.native_handle();
sleep(1); // give the thread time to get into its 'expensive computation';
// otherwise it'll likely be cancelled right away
// now, once main returns and t1's destructor is called, the pthreadCancelAndJoin
// functor object will be called, and so the underlying p_thread will be cancelled
// and joined
return 0;
}
pthread_cancel() will cancel your thread when it reaches a "cancellation point" (assuming the cancel type and cancel state are at their default values, which is the case for boost::thread objects); see the pthreads man page for a list of all cancellation points. You'll notice that those cancellation points include many of the more common system calls, like write, read, sleep, send, recv, wait, etc.
If your 'expensive computation' includes any of those calls down at its lowest level (e.g. in the code sample, printf eventually calls write), it will be cancelled.
Best of all, Valgrind reports no memory leaks or memory errors with this solution.
Finally, a note about your misconception in your question:
I had figured the joins would be treated as an interruption point...
join, or any of the boost::thread interruption functions, for that matter, is only treated as an interruption point for the thread that calls it. Since your main thread is calling join(), the main thread is the thread that experiences the interruption point, not the thread that it is trying to join. E.g. if you call thread1.interrupt() in some thread and then thread1 calls thread2.join(), then thread1 is the one that gets interrupted.

Thread ending unexpectedly. c++

I'm trying to get a hold on pthreads. I see some people also have unexpected pthread behavior, but none of the questions seemed to be answered.
The following piece of code should create two threads, one which relies on the other. I read that each thread will create variables within their stack (can't be shared between threads) and using a global pointer is a way to have threads share a value. One thread should print it's current iteration, while another thread sleeps for 10 seconds. Ultimately one would expect 10 iterations. Using break points, it seems the script just dies at
while (*pointham != "cheese"){
It could also be I'm not properly utilizing code blocks debug functionality. Any pointers (har har har) would be helpful.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;
string hamburger = "null";
string * pointham = &hamburger;
void *wait(void *)
{
int i {0};
while (*pointham != "cheese"){
sleep (1);
i++;
cout << "Waiting on that cheese " << i;
}
pthread_exit(NULL);
}
void *cheese(void *)
{
cout << "Bout to sleep then get that cheese";
sleep (10);
*pointham = "cheese";
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_create(&threads[0], NULL, cheese, NULL);
pthread_create(&threads[1], NULL, wait, NULL);
return 0;
}
The problem is that you start your threads, then exit the process (thereby killing your threads). You have to wait for your threads to exit, preferably with the pthread_join function.
If you don't want to have to join all your threads, you can call pthread_exit() in the main thread instead of returning from main().
But note the BUGS section from the manpage:
Currently, there are limitations in the kernel implementation logic for
wait(2)ing on a stopped thread group with a dead thread group leader.
This can manifest in problems such as a locked terminal if a stop sig‐
nal is sent to a foreground process whose thread group leader has
already called pthread_exit().
According to this tutorial:
If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
So, you shouldn't end the main function with the statement return 0;. But you should use pthread_exit(NULL); instead.
If this doesn't work with you, you may need to learn about joining threads here.

Threading in C++ to keep two functions running parallely

I have a code congaing two functions func1 and func2. Role of both the function is same. Keep reading a directory continuously and write the names of file present in their respective log files. Both functions are referring a common log function to write the logs. I want to use introduce threading in my code such that both of them keep on running parallely but both should not access the log function at same time. How to achieve that?
This is a classic case of needing a mutex.
void WriteToLog(const char *msg)
{
acquire(mutex);
logfile << msg << endl;
release(mutex);
}
The above code won't "copy and paste" into your system, since mutexes are system specific - pthread_mutex would be the choice if you are using pthreads. C++11 has it's own mutex and thread functionality, and Windows has another variant.
From Sajal's comments:
tried pthread_create(&thread1, NULL, start_opca, &opca); pthread_join( thread1, NULL); pthread_create(&thread2, NULL, start_ggca, &ggca); pthread_join( thread2, NULL);
But the problem with this is that it will wait for one thread to finish before starting next. I don't want that.
the join function blocks the calling thread, until the thread you call join for, finishes. In your case, calling join on the first thread before creating the second, guarantees that the first thread will end before the second one begins.
You should create the two threads first, then join them both (instead of interspersing the creations and join of both).
Additionally, the access to the log should be extracted into common code for both (a logging function, a logging class etc. Within the extracted code, the log access should be guarded using a mutex.
If you have an implementation (partially) supporting c++11, you should use std::thread and std::mutex for this. Otherwise, you should use boost::thread. If you have access to neither, use pthreads under linux.
On linux, you will need to use pthreads
Since both threads are reading/writing from/to I/O (reading dirs and writing log files) there's no need for multi-threading: you gain no speed improvement parallelizing the task since every I/O access is enqueued at lower levels.
This C language Code may give you some hint. To answer your question:
You should use mutex in pthread to make sure that the log file could only be access by one thread at the same time.
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t LogLock = PTHREAD_MUTEX_INITIALIZER;
char* LogFileName= "test.log";
void* func_tid0( void* a) {
int i;
for(i=0; i < 50; i++ ) {
pthread_mutex_lock(&LogLock);
fprintf((FILE*)a, "write to log by thread0:%d\n", i);
pthread_mutex_unlock(&LogLock);
}
}
void* func_tid1(void* a) {
int i;
for(i=0; i < 50; i++ ) {
pthread_mutex_lock(&LogLock);
fprintf((FILE*)a, "write to log by thread1:%d\n", i);
pthread_mutex_unlock(&LogLock);
}
}
int main() {
pthread_t tid0, tid1;
FILE* fp=fopen(LogFileName, "wb+");
pthread_create(&tid0, NULL, func_tid0, (void*) fp );
pthread_create(&tid1, NULL, func_tid1, (void*) fp );
void* ret;
pthread_join(tid0, &ret);
pthread_join(tid1, &ret);
}
Your another question isn't exist.
Because the main thread is suspend at your first pthread_join, but it's not mean the second thread doesn't run. Actually the second thread is beginning at pthread_create(thread1).
And actually pthread_mutex casuses your program serial.

Avoding multiple thread spawns in pthreads

I have an application that is parallellized using pthreads. The application has a iterative routine call and a thread spawn within the rountine (pthread_create and pthread_join) to parallelize the computation intensive section in the routine. When I use an instrumenting tool like PIN to collect the statistics the tool reports statistics for several threads(no of threads x no of iterations). I beleive it is because it is spawning new set of threads each time the routine is called.
How can I ensure that I create the thread only once and all successive calls use the threads that have been created first.
When I do the same with OpenMP and then try to collect the statistics, I see that the threads are created only once. Is it beacause of the OpenMP runtime ?
EDIT:
im jus giving a simplified version of the code.
int main()
{
//some code
do {
compute_distance(objects,clusters, &delta); //routine with pthread
} while (delta > threshold )
}
void compute_distance(double **objects,double *clusters, double *delta)
{
//some code again
//computation moved to a separate parallel routine..
for (i=0, i<nthreads;i++)
pthread_create(&thread[i],&attr,parallel_compute_phase,(void*)&ip);
for (i=0, i<nthreads;i++)
rc = pthread_join(thread[i], &status);
}
I hope this clearly explains the problem.
How do we save the thread id and test if was already created?
You can make a simple thread pool implementation which creates threads and makes them sleep. Once a thread is required, instead of "pthread_create", you can ask the thread pool subsystem to pick up a thread and do the required work.. This will ensure your control over the number of threads..
An easy thing you can do with minimal code changes is to write some wrappers for pthread_create and _join. Basically you can do something like:
typedef struct {
volatile int go;
volatile int done;
pthread_t h;
void* (*fn)(void*);
void* args;
} pthread_w_t;
void* pthread_w_fn(void* args) {
pthread_w_t* p = (pthread_w_t*)args;
// just let the thread be killed at the end
for(;;) {
while (!p->go) { pthread_yield(); }; // yields are good
p->go = 0; // don't want to go again until told to
p->fn(p->args);
p->done = 1;
}
}
int pthread_create_w(pthread_w_t* th, pthread_attr_t* a,
void* (*fn)(void*), void* args) {
if (!th->h) {
th->done = 0;
th->go = 0;
th->fn = fn;
th->args = args;
pthread_create(&th->h,a,pthread_w_fn,th);
}
th->done = 0; //make sure join won't return too soon
th->go = 1; //and let the wrapper function start the real thread code
}
int pthread_join_w(pthread_w_t*th) {
while (!th->done) { pthread_yield(); };
}
and then you'll have to change your calls and pthread_ts, or create some #define macros to change pthread_create to pthread_create_w etc....and you'll have to init your pthread_w_ts to zero.
Messing with those volatiles can be troublesome though. you'll probably need to spend some time getting my rough outline to actually work properly.
To ensure something that several threads might try to do only happens once, use pthread_once(). To ensure something only happens once that might be done by a single thread, just use a bool (likely one in static storage).
Honestly, it would be far easier to answer your question for everyone if you would edit your question – not comment, since that destroys formatting – to contain the real code in question, including the OpenMP pragmas.

Simple C++ Threading

I am trying to create a thread in C++ (Win32) to run a simple method. I'm new to C++ threading, but very familiar with threading in C#. Here is some pseudo-code of what I am trying to do:
static void MyMethod(int data)
{
RunStuff(data);
}
void RunStuff(int data)
{
//long running operation here
}
I want to to call RunStuff from MyMethod without it blocking. What would be the simplest way of running RunStuff on a separate thread?
Edit: I should also mention that I want to keep dependencies to a minimum. (No MFC... etc)
#include <boost/thread.hpp>
static boost::thread runStuffThread;
static void MyMethod(int data)
{
runStuffThread = boost::thread(boost::bind(RunStuff, data));
}
// elsewhere...
runStuffThread.join(); //blocks
C++11 available with more recent compilers such as Visual Studio 2013 has threads as part of the language along with quite a few other nice bits and pieces such as lambdas.
The include file threads provides the thread class which is a set of templates. The thread functionality is in the std:: namespace. Some thread synchronization functions use std::this_thread as a namespace (see Why the std::this_thread namespace? for a bit of explanation).
The following console application example using Visual Studio 2013 demonstrates some of the thread functionality of C++11 including the use of a lambda (see What is a lambda expression in C++11?). Notice that the functions used for thread sleep, such as std::this_thread::sleep_for(), uses duration from std::chrono.
// threading.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
int funThread(const char *pName, const int nTimes, std::mutex *myMutex)
{
// loop the specified number of times each time waiting a second.
// we are using this mutex, which is shared by the threads to
// synchronize and allow only one thread at a time to to output.
for (int i = 0; i < nTimes; i++) {
myMutex->lock();
std::cout << "thread " << pName << " i = " << i << std::endl;
// delay this thread that is running for a second.
// the this_thread construct allows us access to several different
// functions such as sleep_for() and yield(). we do the sleep
// before doing the unlock() to demo how the lock/unlock works.
std::this_thread::sleep_for(std::chrono::seconds(1));
myMutex->unlock();
std::this_thread::yield();
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
// create a mutex which we are going to use to synchronize output
// between the two threads.
std::mutex myMutex;
// create and start two threads each with a different name and a
// different number of iterations. we provide the mutex we are using
// to synchronize the two threads.
std::thread myThread1(funThread, "one", 5, &myMutex);
std::thread myThread2(funThread, "two", 15, &myMutex);
// wait for our two threads to finish.
myThread1.join();
myThread2.join();
auto fun = [](int x) {for (int i = 0; i < x; i++) { std::cout << "lambda thread " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } };
// create a thread from the lambda above requesting three iterations.
std::thread xThread(fun, 3);
xThread.join();
return 0;
}
CreateThread (Win32) and AfxBeginThread (MFC) are two ways to do it.
Either way, your MyMethod signature would need to change a bit.
Edit: as noted in the comments and by other respondents, CreateThread can be bad.
_beginthread and _beginthreadex are the C runtime library functions, and according to the docs are equivalent to System::Threading::Thread::Start
Consider using the Win32 thread pool instead of spinning up new threads for work items. Spinning up new threads is wasteful - each thread gets 1 MB of reserved address space for its stack by default, runs the system's thread startup code, causes notifications to be delivered to nearly every DLL in your process, and creates another kernel object. Thread pools enable you to reuse threads for background tasks quickly and efficiently, and will grow or shrink based on how many tasks you submit. In general, consider spinning up dedicated threads for never-ending background tasks and use the threadpool for everything else.
Before Vista, you can use QueueUserWorkItem. On Vista, the new thread pool API's are more reliable and offer a few more advanced options. Each will cause your background code to start running on some thread pool thread.
// Vista
VOID CALLBACK MyWorkerFunction(PTP_CALLBACK_INSTANCE instance, PVOID context);
// Returns true on success.
TrySubmitThreadpoolCallback(MyWorkerFunction, context, NULL);
// Pre-Vista
DWORD WINAPI MyWorkerFunction(PVOID context);
// Returns true on success
QueueUserWorkItem(MyWorkerFunction, context, WT_EXECUTEDEFAULT);
Simple threading in C++ is a contradiction in terms!
Check out boost threads for the closest thing to a simple approach available today.
For a minimal answer (which will not actually provide you with all the things you need for synchronization, but answers your question literally) see:
http://msdn.microsoft.com/en-us/library/kdzttdcb(VS.80).aspx
Also static means something different in C++.
Is this safe:
unsigned __stdcall myThread(void *ArgList) {
//Do stuff here
}
_beginthread(myThread, 0, &data);
Do I need to do anything to release the memory (like CloseHandle) after this call?
Another alternative is pthreads - they work on both windows and linux!
CreateThread (Win32) and AfxBeginThread (MFC) are two ways to do it.
Be careful to use _beginthread if you need to use the C run-time library (CRT) though.
For win32 only and without additional libraries you can use
CreateThread function
http://msdn.microsoft.com/en-us/library/ms682453(VS.85).aspx
If you really don't want to use third party libs (I would recommend boost::thread as explained in the other anwsers), you need to use the Win32API:
static void MyMethod(int data)
{
int data = 3;
HANDLE hThread = ::CreateThread(NULL,
0,
&RunStuff,
reinterpret_cast<LPVOID>(data),
0,
NULL);
// you can do whatever you want here
::WaitForSingleObject(hThread, INFINITE);
::CloseHandle(hThread);
}
static DWORD WINAPI RunStuff(LPVOID param)
{
int data = reinterpret_cast<int>(param);
//long running operation here
return 0;
}
There exists many open-source cross-platform C++ threading libraries you could use:
Among them are:
Qt
Intel
TBB Boost thread
The way you describe it, I think either Intel TBB or Boost thread will be fine.
Intel TBB example:
class RunStuff
{
public:
// TBB mandates that you supply () operator
void operator ()()
{
// long running operation here
}
};
// Here's sample code to instantiate it
#include <tbb/tbb_thread.h>
tbb::tbb_thread my_thread(RunStuff);
Boost thread example:
http://www.ddj.com/cpp/211600441
Qt example:
http://doc.trolltech.com/4.4/threads-waitconditions-waitconditions-cpp.html
(I dont think this suits your needs, but just included here for completeness; you have to inherit QThread, implement void run(), and call QThread::start()):
If you only program on Windows and dont care about crossplatform, perhaps you could use Windows thread directly:
http://www.codersource.net/win32_multithreading.html