views:

93

answers:

3

I searched for examples on how to create a simple multithreaded app that does something similar to this:

#include <iostream>
using namespace std;
int myConcurrentFunction( )
{
    while( 1 )
    {
         cout << "b" << endl;
    }
}
int main( )
{
    // Start a new thread for myConcurrentFunction
    while( 1 )
    {
         cout << "a" << endl;
    }
}
  • How can I get the above to output a and b "randomly" by starting a new thread instead of just calling myConcurrentFunction normally?

I mean: What is the minimal code for it? Is it really only one function I have to call? What files do I need to include?

I use MSVC 2010, Win32

+2  A: 

The easiest is _beginthread. Just focus on how they create the thread in their example, it's not as complicated as it seems at a first glance.

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

using namespace std;
void myConcurrentFunction(void *dummy)
{
    while( 1 )
    {
         cout << "b" << endl;
    }
}

int main( )
{
    _beginthread(myConcurrentFunction, 0, NULL);
    while( 1 )
    {
         cout << "a" << endl;
    }
}
IVlad
+1 IVlad, good answer.
Byron Whitlock
+1  A: 

It is more complicated than that. For one, the thread function must return a DWORD, and take an LPVOID parameters.

Take a look at the code from MSDN for more details.

Byron Whitlock
Doesn't seem that complicated according to IVlads answer..
Con Current
yes his is much simpler. Use that one unless you are writing pure C. :D
Byron Whitlock
A: 

BTW, why thread when you just need random sprinkiling of 'a' & 'b'.

int randomSprinkling() { char val[2]={'a','b'};

int i = 0;
while( ++i < 100  ) 
{
    std::cout << val[rand()%2] << std::endl; 
} 
return 0;

}

Zhinkaas
Ha ha, your mind is not the fastest eh? Or you are a troll... You read the question title? Multitasking?
Con Current
@Con Current: I don't think you need to be so mean to the answerer.
Maulrus
Speaking of trolling, do you often call people stupid when they try to help you? Reported your comment as offensive. Please keep in mind that this isn't a kindergarten.
jalf
@con current. I am not fastest, but practical and dislike trolls as much as you do. You can see how many points I have earned in last 1 month for the proof :-) Some times, people need solutions and they have some half-baked idea of doing it in a particular way only. The asker may just needed what I provided, but he thought that this could be achiieved via threads only.
Zhinkaas