i DO have searched the google to do multithreaded programming using c++ and found there were few like the ones supported in BOOST libraries and zthreads ..
I would be glad if u guys could help me in suggesting much better ways in doing so .

Recommended Answers

All 18 Replies

What OS?

i am ok with windows or linux .
Since i am a naive in this field i would prefer something that is basic and easy to use.

Just use CreateThread() -- its simple to use because most of the parameters are 0 or NULL. I have not used the boost library, so I don't know how they work.

Creating threads is easy, making them work together may be more problematic. If two or more threads have to access a common object then you will have to implement thread synchronization via mutex or critical sections.

i theoretically understand mutex , semaphores and the related concepts as i had a complete subject on OS this semester .
I have devised my own methods of theoretically solving dinner philosophers problem and readers/writers problems which are very well know in deadlocks
But now i want to do this thing practically , just don't have any idea on how to proceed.
I would be grateful if u could enlighten me on how to start with this.

Aren't there any examples in your OS-course book? I had an OS course(outside of my normal curriculum as I study mechanical engineering) too this semester, which included a 'lab' where we were given the task to write a multi threaded assignment.
I would suggest using the 'pthread' library, especially in Linux it is commonly used as the p stands for POSIX.
You can add threads easily to your application but as Dragon said.. the fun part starts when they share resources.

I don't think it is necessary to explain pthread, there are tons of good tutorials on the web.

i DO have searched the google to do multithreaded programming using c++ and found there were few like the ones supported in BOOST libraries and zthreads ..
I would be glad if u guys could help me in suggesting much better ways in doing so .

Hi,

Firstly, wait! Do not EVER use CreateThread(). I say it because it's an API call and will be available for execution, even for a program which uses the single threaded version of the CRT! The results may not be pleasing. By calling the compiler provided function to create a thread, you will never be able to commit such a blunder, because the compiler will catch you (the thread creation call won't be available for use while linking to the single threaded version of the CRT). Also, initializing the CRT won't happen with CreateThread(). The MSDN documentation for CreateThread() neglects to mention this extremely important trait.

If you're using the Visual C++ compiler, you should use _beginthread or _beginthreadex (recommended) or if you're using MFC, you MUST use AfxBeginThread. If you're using a different compiler, check with the compiler documentation to find out what function does it provide to create threads.

Explaining these things in detail is possibly out of the context of this thread.

There are several good articles allover the web. Here's one for instance: Multithreading Tutorial

Here's a whole lot of stuff: Threads, Processes and IPC section

Threading is an extremely interesting aspect of programming. Have fun. :)

thanks guys , with ur help i could write my first thread program , but here is the problem .


i got the first program

here is the code

#include<iostream.h>
#include<windows.h>
#include<process.h>

using namespace std;

void silly (void *);

int main ()
{
    cout<<" now in main function  ";

    _beginthread( silly , 0 , (void *)12) ;

    silly ( (void *) -5 ) ;
    Sleep (100) ;
    return 0;
}

void silly ( void * arg )
{
    cout<<" this is the silly function "<< (INT_PTR)arg ;
}

i use MInGW compiler and currently working in windows

but the problem is the output was something like this

now in main function t thhisi si si sthe sitllyh ef uncstioninlly function1-2
5

honestly i dont even know whether this output is correct or not , and if this is the right one well then why is it executing so weirdly ?

thanks guys , with ur help i could write my first thread program , but here is the problem .


i got the first program

here is the code

#include<iostream.h>
#include<windows.h>
#include<process.h>

using namespace std;

void silly (void *);

int main ()
{
    cout<<" now in main function  ";

    _beginthread( silly , 0 , (void *)12) ;

    silly ( (void *) -5 ) ;
    Sleep (100) ;
    return 0;
}

void silly ( void * arg )
{
    cout<<" this is the silly function "<< (INT_PTR)arg ;
}

i use MInGW compiler and currently working in windows

but the problem is the output was something like this

honestly i dont even know whether this output is correct or not , and if this is the right one well then why is it executing so weirdly ?

Umm... The output was something like what?! The output was blank?

Which might possibly mean that the program (the main thread) terminated before the worker thread was scheduled to run (or after the worker thread was scheduled to run AND before it actually started to run).

I seriously think that I cannot be teaching you the asynchronous nature of threaded applications, context switching and other gotchas involved in multithreading here in a post like this.

I suggest that you read a good book on the said topic. It will cover things in an orderly fashion, and with suitable examples.

the output is mentioned in my last edited post.
Well sorry for that .

I have read OS by GALVIN , but that is not suitable for pragmatic programmers like me .
can u suggest some good books which practically teaches on how to implement this and also incorporate valuable topics like IPC and MPI .

Well you hit the nail on the head when we mentioned that problems can arise in multithreaded programming.

the silly function is first executed, in a separate thread and then immediately again in the main thread.
cout works by filling a buffer, so while the separate thread is filling the buffer, the main thread starts filling it too.
So if you want to print it sequentially, you need to 'protect' the cout call.

EDIT:

Do you mean the 'Operating System Concepts' book by Silberschatz and Galvin? As this is what we use in our OS class.

now in main function t thhisi si si sthe sitllyh ef uncstioninlly function1-2

The output is torn apart, because you've called the silly function within the main thread, AFTER the thread itself has been asked to be scheduled.

So, the main thread is executing the silly function, and SIMULTANEOUSLY the worker thread which got spawned is also executing the silly function. And this is knocking the socks out of the output. Disable the call to the silly function after the _beginthread call (which I think you've done by mistake).

I don't remember myself reading any book specific to threading. Why not read the articles I pointed out in an earlier reply? That must get you started. Also, if you buy a good book on Win32, it would cover threading as well! (consider something like "Programming Windows" by Charles Petzold).

Do you mean the 'Operating System Concepts' book by Silberschatz and Galvin? As this is what we use in our OS class

yep thats the one .

Well since i have decided to jump into this , i would be more adventurous and not confine myself to windows , so is there ne book on linux ,which can teach this thing in depth ?

Hi,

Firstly, wait! Do not EVER use CreateThread(). I say it because it's an API call and will be available for execution, even for a program which uses the single threaded version of the CRT! The results may not be pleasing. By calling the compiler provided function to create a thread, you will never be able to commit such a blunder, because the compiler will catch you (the thread creation call won't be available for use while linking to the single threaded version of the CRT).

Of course anything can be dangerous if you just blindly toss api function calls at your program with no thought. CreateThread() works great in multithreaded environments. I have used it many many times over the past 10 years in MFC programs with Visual Studio compilers. There has never ever been a problem with it.

Also, initializing the CRT won't happen with CreateThread(). The MSDN documentation for CreateThread() neglects to mention this extremely important trait.

I'm not sure that is even relevant to the issue. Why would I want to initialize the CRT just to do some number crunching in another thread? The CRT has already been initialized on program startup by the main thread.

If you're using the Visual C++ compiler, you should use _beginthread or _beginthreadex (recommended) or if you're using MFC, you MUST use AfxBeginThread.

It depends -- CreateThread() works ok in MFC if the new thread will not be interacting with MFC objects, such as the new thread can not create new MFC windows.

yep thats the one .

Well since i have decided to jump into this , i would be more adventurous and not confine myself to windows , so is there ne book on linux ,which can teach this thing in depth ?

If you want to write os-independent code then use the Boost library classes and functions.

Of course anything can be dangerous if you just blindly toss api function calls at your program with no thought.

Well, he's "blind" and has no thought, because he's a complete rookie with multithreading. How is he supposed to know this fact? Which is why I warned him about it.

CreateThread() works great in multithreaded environments. I have used it many many times over the past 10 years in MFC programs with Visual Studio compilers. There has never ever been a problem with it.

You've been doing it wrong for about 10 years. A program doesn't crash doesn't mean it's working "great".

Win32 Q&A (Microsoft systems journal), July 1999:

An enquirer: I have been writing Win32®-based applications for years now and have always created my threads by calling the CreateThread function. Recently a coworker told me that I should not call CreateThread, but to use _beginthreadex instead. So far my apps have all worked just fine with CreateThread. Can you explain what all this is about?

Jeffrey Richter: Well, first, I must tell you that your coworker is correct. If you are writing Win32-based applications using C or C++, you should create threads using the _beginthreadex function and not use CreateThread.

Link to the Q&A: http://www.microsoft.com/msj/0799/Win32/Win320799.aspx

Take a look at the Remarks section of the documentation for CWinThread.

MFC maintains per thread handle maps, and it relies totally on calls to the MFC thread functions to do it correctly. By not using the MFC thread functions and calling something like CreateThread(), this mechanism is totally bypassed! While you will get away if not using MFC functions within the thread, if you have call an MFC function within the thread in the future, you've opened up a new fatal bug introduced by a call to CreateThread(). Simply by choosing the right call, you can totally avoid this.

You could verify all this by viewing the MFC source code. Explaining this in great detail here is impossible. I don't feel like doing it to prove it to somebody. Check with Windows via C/C++, in which Jeffrey Richter has explained this in great detail and you'll know who of us is right on this.

I'm not sure that is even relevant to the issue. Why would I want to initialize the CRT just to do some number crunching in another thread? The CRT has already been initialized on program startup by the main thread.

This is just crude! If the program was using the single threaded version of the CRT (the program would have compiled, because a call to CreateThread was made instead of _beginthreadex and the compiler couldn't stop you). Now the thread is going to mess up the CRT in ways you least expect. But, a call to _beginthreadex instead of CreateThread will take care of this! It's also explained in the Microsoft Win32 Q&A I linked you to earlier.

It depends -- CreateThread() works ok in MFC if the new thread will not be interacting with MFC objects, such as the new thread can not create new MFC windows.

That's an extremely hideous programming practice - to call CreateThread() and to remember all the time not to call MFC functions within the thread function. When AfxBeginThread is the correct way to do it, I see absolutely no reason to CreateThread while using MFC - not to mention you'll bypass the entire MFC mechanism which sets up and manage the internal states of each different thread.

I have no desire to continue this conversation for argument's sake. I've written all this for the benefit of the OP, who is a newbie. And if you still think it's a great idea to use CreateThread in an MFC program and and suggest it to a noob as well, you may check this up: The n Habits of Highly Defective Programs, refer to books - Windows via C/C++ and Windows Internals. All of them have discussed my points in detail.

commented: Very good points. +25

well thanks both of u guys for exchanging such arcane (atleast for me) information .
Again i am here with a stupid problem of mine .
well i got to know about pthreads and i ran a sample code for that in ubuntu 9.04 (which i installed for sake of multi threaded programs ) .

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS	5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
  printf("In main: creating thread %ld\n", t);
  rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
  if (rc){
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
    }
  }
pthread_exit(NULL);
}

And here is the output for it.

rahul $ gcc p1.c
/tmp/ccG7qvx1.o: In function `main':
p1.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

honeslty have no idea on how this came up . Is something wrong with my PC ?

Nothing is wrong with you PC, but it seems it would be wise for you to take a step back, and learn more general C practices before jumping into multithreaded programming.

But here is the answer anyway:
pthread is a library, which means that the code is in some external DLL. Now your compiler complains that you call pthread_create but it has no idea where it can find this function(including the header file will only tell the compiler what the function looks like, it wont tell it where to find it).

So you need to hand over the flag: '-lpthread' to your compiler. So:
'gcc p1.c -lpthread'

But I highly suggest that you learn more about how to compile / link. It was also a problem in our OS class that for most students this was their first encounter with C but they were expected to write an application already.

i would certainly try out that one.. ne ways thanks pals . all of u have been of great help .
i got the direction i wanted , i will take it from here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.