serjM
August 18th, 2008, 03:58 PM
Hy, I have a simple C++ program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream.h>
void *print_message_function1( void *ptr );
void *print_message_function2( void *ptr );
int main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
iret1 = pthread_create( &thread1, &attr, print_message_function1, (void*) message1);
iret2 = pthread_create( &thread2, &attr, print_message_function2, (void*) message2);
pthread_attr_destroy(&attr);
return 0;
}
void *print_message_function1( void *ptr )
{
char *message;
message = (char *) ptr;
sched_yield();
for(int i=0;i<100;i++)
cout << i << endl << flush;
pthread_exit((void *) 0);
}
void *print_message_function2( void *ptr )
{
char *message;
message = (char *) ptr;
for(int i=0;i<100;i++)
cout << i << endl << flush;
pthread_exit((void *) 0);
}
My threads are running as two functions, their output is not mixing.
Instead of (for example) 0 1 2 0 3 1 2 3 the program outputs 0 1 2 3 0 1 2 3.
How I can make them to run in the same time, I must change something in the scheduling method?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream.h>
void *print_message_function1( void *ptr );
void *print_message_function2( void *ptr );
int main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
iret1 = pthread_create( &thread1, &attr, print_message_function1, (void*) message1);
iret2 = pthread_create( &thread2, &attr, print_message_function2, (void*) message2);
pthread_attr_destroy(&attr);
return 0;
}
void *print_message_function1( void *ptr )
{
char *message;
message = (char *) ptr;
sched_yield();
for(int i=0;i<100;i++)
cout << i << endl << flush;
pthread_exit((void *) 0);
}
void *print_message_function2( void *ptr )
{
char *message;
message = (char *) ptr;
for(int i=0;i<100;i++)
cout << i << endl << flush;
pthread_exit((void *) 0);
}
My threads are running as two functions, their output is not mixing.
Instead of (for example) 0 1 2 0 3 1 2 3 the program outputs 0 1 2 3 0 1 2 3.
How I can make them to run in the same time, I must change something in the scheduling method?