PDA

View Full Version : Some confusion about POSIX threads



manasij7479
08-13-2011, 08:31 AM
I decided to learn threading for a program of mine which seems (I may be wrong) to scream its necessity.
I thought threads were supposed to be executed in parallel in machines having more than one core.
So why am I getting the following output from the following program?
[I left out joining for now...Does that play a role here ?]


#define _REENTRANT
#include<pthread.h>
#include<iostream>
using namespace std;

void* foo(void* arg);
int main()
{
int return_value;
pthread_t reference;
return_value= pthread_create(&reference,NULL,foo,NULL);
if(return_value!=0)
{
cout<<"Creation Failed";
return 1;
}
int x(10);
while(x--)
cout<<8;


return 0;

}
void* foo(void* arg)
{
//cout<<"Thread Running.."<<endl;
int x(10);

while(x--)
cout<<9;
return (void*)(arg);
}

The output is
99999999998888888888 instead of my expected jumble of 9s and 8s. Why is it so ?

MK27
08-13-2011, 09:28 AM
You want to use pthread_detach() after pthread_create.

Also: there are no guarantees about the order of events with separate threads. Do not even presume that you will get:

98989898989

You are just as likely to get 999999888888 again, or 888888999999. If you need to guarantee a sequence, you will need to use mutex locks. Without locking, threads are fine for doing things that do not have to happen in any particular order (because they won't).