Here is piece (very simplified, with global var's and other "smells") of C code, which uses posix barrier primitive to sincronize thread start.
#include <pthread.h>
#include <stdio.h>
pthread_barrier_t barrier;
void* thread_func(void* aArgs)
{
pthread_barrier_wait(&barrier);
printf("Entering thread %p\n", (void*)pthread_self());
int i;
for(i = 0 ; i < 5; i++)
printf("val is %d in thread %p \n", i, (void*)pthread_self());
}
int main()
{
pthread_t thread_1, thread_2;
pthread_barrier_init(&barrier, NULL, 2);
pthread_create(&thread_1, NULL, (void*)thread_func, NULL);
printf("Thread %p created\n", (void*)thread_1);
usleep(500);
pthread_create(&thread_2, NULL, (void*)thread_func, NULL);
printf("Thread %p created\n", (void*)thread_2);
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
pthread_barrier_destroy(&barrier);
return 0;
}
I can't understand, why "Entering thread ..." string occurs not simultaneously in the output? When i run above programm, usually get alike output:
Thread 0xb74fdb40 created
Thread 0xb6cfcb40 created
Entering thread 0xb6cfcb40
val is 0 in thread 0xb6cfcb40
val is 1 in thread 0xb6cfcb40
val is 2 in thread 0xb6cfcb40
val is 3 in thread 0xb6cfcb40
val is 4 in thread 0xb6cfcb40
Entering thread 0xb74fdb40
val is 0 in thread 0xb74fdb40
val is 1 in thread 0xb74fdb40
val is 2 in thread 0xb74fdb40
val is 3 in thread 0xb74fdb40
val is 4 in thread 0xb74fdb40
What i expect, is simultaneously starting of two threads, and appearing of "Entering thread ..." strings in sequence in the output. Compile it with: gcc barrier.c -pthread
What i'm doing wrong with that?